Shared and race conditions

Michael michael at toohuman.io
Wed Nov 29 16:19:05 UTC 2017


On Wednesday, 29 November 2017 at 16:13:13 UTC, Wanderer wrote:
> 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?

I unfortunately cannot answer your question but I am noticing 
that running the code with DMD gives you an unordered sequence of 
IDs, but running with DMD-nightly gives you a sequence in the 
correct order. I wonder what has changed to do with threads that 
causes this difference between compiler versions.


More information about the Digitalmars-d-learn mailing list