Threading bugs

Johan Granberg lijat.meREM at OVEgmail.com
Tue Jun 26 14:02:38 PDT 2007


Tristam MacDonald wrote:

> And score 10 for forgetting to explain the problem :)
> 
> Anyway, this code sample should print "starting", star a thread that exits
> immediately, and finally print "ending" as the destructor is called at
> program termination. Instead, it prints "starting" and then does nothing -
> or more precisely hogs the entirety of only one of my 2 cores - and never
> exits.
> 
> BTW, this is using gdc on a Mac (latest release of gdcmac), so could be a
> pthread specific problem perhaps?
> 
> Tristam MacDonald Wrote:
> 
>> So, I am sure that I must be missing something simple, that is causing my
>> multi-threading code in D fail miserably. I have cut it down to the
>> smallest code sample that exhibits the problem, and I would be grateful
>> if someone could have a look and let me know why...
>> 
>> import std.thread;
>> import std.stdio;
>> 
>> class Main
>> {
>> this() {
>> writefln("starting");
>> 
>> Thread worker = new Thread(&workerMain);
>> worker.start();
>> }
>> ~this() {
>> writefln("ending");
>> }
>> 
>> int workerMain()
>> {
>> // -- disabled in case of deadlock in std.format, but never reached
>> anyway
>> //           writefln("In Thread");
>> return 0;
>> }
>> 
>> Thread worker;
>> }
>> 
>> int main()
>> {
>> Main m = new Main();
>> 
>> return 0;
>> }
>> 
>> 
>>

If you change the main method to this the thread will be run.

int main()
{
        Main m = new Main();

        foreach(t;Thread.getAll())
                if(!t.isSelf())
                        t.wait();

        return 0;
}

The current behavior seams to be that all threads exits when main returns
(or when std.c.stdlib.exit is run). The constructor is not run because the
class is not deleted by you or the garbage collector, there was talk about
this behavior some time ago (maybe last summer) and this is by design,
search the newsgroup or changelog if you want to follow the discussion.


More information about the Digitalmars-d-learn mailing list