GC safety

We call a proc p GC safe when it doesn’t access any global variable that contains GC’ed memory (string, seq, ref or a closure) either directly or indirectly through a call to a GC unsafe proc.

The gcsafe annotation can be used to mark a proc to be gcsafe, otherwise this property is inferred by the compiler. Note that noSideEffect implies gcsafe. The only way to create a thread is via spawn or createThread. The invoked proc must not use var parameters nor must any of its parameters contain a ref or closure type. This enforces the no heap sharing restriction.

Routines that are imported from C are always assumed to be gcsafe. To disable the GC-safety checking the --threadAnalysis:off command line switch can be used. This is a temporary workaround to ease the porting effort from old code to the new threading model.

To override the compiler’s gcsafety analysis a {.cast(gcsafe).} pragma block can be used:

  1. var
  2. someGlobal: string = "some string here"
  3. perThread {.threadvar.}: string
  4. proc setPerThread() =
  5. {.cast(gcsafe).}:
  6. deepCopy(perThread, someGlobal)

See also: