Programming with Hyper-Threading Technology: How to Write Multithreaded Software for Intel IA-32 Processors

In the previous chapter, one example showed how the migration to parallel programming can introduce unexpected problems in code, such such as the problem of false sharing.
This problem demonstrates a curious aspect of the difficulties introduced by parallel programming: they are frequently difficult to anticipate if you don't have specific knowledge of them. And, when encountered, they are difficult to remediate unless you can recognize the specific symptoms. These two aspects are compounded by the greater difficulty of debugging parallel programs. As a result, developers using parallel programming need to be much more attentive to proper coding practices and careful testing, so that they can avoid these traps at the coding stage rather than fixing them later in a cycle of debugging and testing. This chapter examines common parallel programming problems that do not usually appear in single-threaded desktop applications.
As mentioned several times, thread execution is nondeterministic, so you cannot know when a given thread will be run by the operating system. As a result, if you pass a temporary variable to a thread, the value of that variable may have changed by the time the thread is run. Worse yet, the temporary variable might no longer exist, because the function calling the thread may have finished and the data item may have gone out of scope. Let's look at an example. The code in Figure 2.1, and Figure 2.3 for the Pthreads version, started up a series of Windows threads and had...