Thread will get garbage collected?

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 17 00:12:50 PST 2017


On Tuesday, 17 January 2017 at 07:53:32 UTC, thedeemon wrote:
> On Monday, 16 January 2017 at 22:08:56 UTC, JN wrote:
>
>> Am I correctly understanding, that after going out of scope, 
>> it's possible for GC to destroy my thread before the file 
>> finishes loading? How to prevent GC from destroying my thread 
>> before it finishes and make sure the file is loaded completely?
>
> As far as I know, GC never kills threads.


yes. it doesn't matter if a thread is achored or not, it won't be 
killed. it is very easy to check, actually:

import core.thread;
import core.time;
import std.stdio;

void threadStarter (string path) {
   new Thread({
     for (;;) {
       writeln(path);
       Thread.sleep(1.seconds);
     }
   }).start();
}


class A {
   ~this () { import core.stdc.stdio; printf("i'm dead now!\n"); }
}


void main () {
   threadStarter("foo.txt");
   auto a = new A();
   import core.memory : GC;
   for (;;) {
     writeln("collect...");
     GC.collect();
     Thread.sleep(500.msecs);
     a = null;
   }
}


one will eventually see "i'm dead now!", yet "foo.txt" will 
continue to appear.


More information about the Digitalmars-d-learn mailing list