Sharing Data Between Threads
The previous chapter was about threads sharing information through message passing. As mentioned in that chapter, message passing is a safe method of concurrency.
Another method involves more than one thread reading from and writing to the same data. For example, the owner thread can start the worker with the address of a
bool variable, and the worker can determine whether to terminate or not by reading the current value of that variable. Another example would be where the owner starts multiple workers with the address of the same variable so that the variable gets modified by more than one worker.
One of the reasons why data sharing is not safe is race conditions. A race condition occurs when more than one thread accesses the same mutable data in an uncontrolled order. Since the operating system pauses and starts individual threads in unspecified ways, the behavior of a program that has race conditions is unpredictable.
The examples in this chapter may look simplistic. However, the issues that they convey appear in real programs at greater scales. Also, although these examples use the
std.concurrency module, the concepts of this chapter apply to the
core.thread module as well.
Sharing is not automatic
Unlike most other programming languages, data is not automatically shared in D; data is thread-local by default. Although module-level variables may give the impression of being accessible by all threads, each thread actually gets its own copy: