Search⌘ K
AI Features

A Race Condition Example

Discover the impact of race conditions on program correctness when multiple threads share mutable data. Understand how thread scheduling can cause unexpected results and why careful synchronization is necessary to avoid corrupted shared variables in D programming.

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:

D
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 ...