On Wednesday, 22 February 2017 at 08:28:48 UTC, ketmar wrote:
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();
        }
}
this code is invalid. when `~this()` is called, your `mThread` *may* already be dead -- this is how GC works. you *may* *not* access heap-allocated members in `~this()`, this is a bug. it may work sometimes, but it isn't guaranteed.

Agreed, I don't want to have a ~this(), I have added it to prevent my program from hanging. As is often the case with these examples, it is a distillation of a much larger project.

The point is that the thread object could be 20 layers of encapsulation down in a library. The thread could also be added 20 layers down long after the main function was written and tested.

The thread can then prevent the program from exiting on exception or otherwise. If the garbage collector doesn't kill threads, do I need to break all encapsulation to call some sort of finalise or destroy function on every object in case it has a thread object in it ? It would probably be better to have all core.thread.Threads registered in the run time so they can be killed when main exits.

Reply via email to