Threads not garbage collected ?

rikki cattermole via Digitalmars-d digitalmars-d at puremagic.com
Tue Feb 21 21:39:50 PST 2017


On 22/02/2017 6:28 PM, Alex wrote:
> import core.thread;
>
> class A
> {
>     Thread mThread;
>     bool mStopped;
>
>     this()
>     {
>         mThread = new Thread(&run);
>         mThread.start();
>     }
>
>     void run()
>     {
>         while (!mStopped)
>         {
>             //do stuff
>         }
>     }
>     ~this()
>     {
>         mStopped = true;
>         mThread.join();
>     }
> }
>
>
>
> void main()
> {
>     auto a = new A;
>     delete a;        //need this or the program hangs
> }
>
> In both gdc and dmd I need to use manually delete this object or the
> program is blocked after main. Is by design ?
> It seems undesirable, as the thread can be many layers of encapsulation
> down, and they all need manual deletes.

Well, you never told the program to stop without delete.

The thread that you start with (calls the main function) doesn't 
actually have to stay alive throughout the program running, surprise!

Anyway, if you do want something that will stop try:

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

class Foo : Thread {
         bool keepRunning;

         this() {
                 keepRunning = true;
                 super(&run);
         }

         private void run() {
                 while(keepRunning) {
                         sleep(1.seconds);
                         writeln("iterate");
                 }
         }
}

void main() {
         Foo foo = new Foo;
         foo.start;

         Thread.sleep(3.seconds);
         foo.keepRunning = false;
}



More information about the Digitalmars-d mailing list