On Wednesday, 22 February 2017 at 05:39:50 UTC, rikki cattermole
wrote:
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;
}
That is interesting, I did not know that the main thread could
exit without returning control to the calling process.
Maybe this should be the case if we were writing in raw C against
OS threading calls, but in this case I clearly have a thread
Object not just an OS Handle, and I think most people would have
an expectation that the garbage collector looks after deleting
things in a garbage collected language when all the references
are gone.
I have also tested throwing an exception in main, and yes the
program hangs. This is even more of a problem because this
undesirable behaviour may only be observed under exceptional
circumstances.