Shared and race conditions

Wanderer d-wanderer at hitbts.com
Wed Nov 29 16:13:13 UTC 2017


I'm trying to simulate a race condition in D with the following 
code:

(https://run.dlang.io/is/RfOX0I)

```
import std.stdio;
import core.thread;
import std.concurrency;

shared struct IdGen(T)
{
     T id;

     this(T start)
     {
         id = start;
     }

     T next()
     {
         id = id.next();
         return id;
     }
}

struct MyId
{
     uint num;

     shared MyId next()
     {
         return MyId(num + 1);
     }
}

static void getId(shared IdGen!(MyId)* g)
{
     writeln("next: ", g.next());
     writeln("next: ", g.next());
}

void main()
{
     MyId start = {0};
     auto g = IdGen!(MyId)(start);

     auto num = 12;
     for (auto i = 0; i < num; i++)
     {
         spawn(&getId, &g);
     }

     thread_joinAll();
     writeln("Done");
}
```

But all I get is correct IDs without any sign of a race (i.e. 
duplicate ids).
Does compiler add synchronization for `shared` data?


More information about the Digitalmars-d-learn mailing list