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

As discussed in Chapter 2, launching a thread only asks the operating system's scheduler to schedule the thread for execution. Once this request has been received by the scheduler, the vagaries caused by other factors such as the operating system itself, the available execution resources, the thread's priority, and so forth determine when exactly execution starts. As a result, any assumptions about the timing of thread execution are bound to be fallacious. And so, if you have to coordinate or synchronize execution between two or more threads, you have to devise mechanisms for this purpose.
If you look at the screen output in Figure 2.2, you will notice that the words "Press any key to exit " appear before threads 7 and 8 have finished executing. As can be seen in the listing in Figure 2.1, the request to press a key is issued only after the threads have all been launched. Suppose it was important for this program to request the key press only after all the threads had finished. How would this be accomplished? A common way, although one that has important drawbacks, is the spin wait.
A spin wait is quite simply a loop that spins, or loops, while waiting for an event to happen. In the listing shown in Figure 2.1, you could have inserted a loop that spun while waiting for a variable to indicate all threads had completed. Let's look at a simple, but incorrect, approach to...