...

/

A Race Condition Example

A Race Condition Example

Let’s look at a race condition example.

We'll cover the following...

The correctness of the program requires extra attention when mutable data is shared between threads.

Example

To see an example of a race condition, let’s consider multiple threads sharing the same mutable variable. The threads in the following program receive the addresses as two variables and swap their values a large number of times:

Press + to interact
import std.stdio;
import std.concurrency;
import core.thread;
void swapper(shared(int) * first, shared(int) * second) {
foreach (i; 0 .. 10_000) {
int temp = *second;
*second = *first;
*first = temp;
}
}
void main() {
shared(int) i = 1;
shared(int) j = 2;
writefln("before: %s and %s", i, j);
foreach (id; 0 .. 10) {
spawn(&swapper, &i, &j);
}
// Wait for all threads to finish their tasks
thread_joinAll();
writefln("after : %s and %s", i, j);
}

Although the program above gets compiled successfully, in most cases it would work incorrectly. Observe that it starts ten threads that all access the same two variables i and j. As a result ...