Shared and race conditions
Steven Schveighoffer
schveiguy at yahoo.com
Wed Nov 29 16:33:50 UTC 2017
On 11/29/17 11:13 AM, Wanderer wrote:
> I'm trying to simulate a race condition in D with the following code:
[snip]
> But all I get is correct IDs without any sign of a race (i.e. duplicate
> ids).
> Does compiler add synchronization for `shared` data?
Using the compiler switch -vcg-ast, I see no synchronization of these
methods.
Races are by definition unpredictable. What has to happen in your case
is one of 2 things:
1. The thread context switches out after the next() call, but before the
assignment. This is very very unlikely given the small number of
instructions the thread executes (the OS isn't about to context switch
out a thread it just switched into execution mode).
2. Two threads running on separate cores both assign at the exact same
time, and they race on the data, one overwriting the other in memory.
Note that executing 12 threads in concurrency isn't going to be a very
stressful case for this race. Yes, it's probably more than the cores on
your machine, but it's also a very small number of threads.
Note also that even when there is a possibility of a race, it may be a
long time before you see any errant behavior. I'd try more threads, and
run the whole test in a loop. At the end of each loop iteration (after
all the threads are completed), verify that the number has incremented
by the correct amount. Stop only after it sees a race has happened.
You may run for minutes until you see a race. You may never see one.
That's the nature of the thing :)
-Steve
More information about the Digitalmars-d-learn
mailing list