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

If you look at the output in Figure 2.2, you'll notice that the threads' execution is interwoven. This generates results such as this one, taken from that figure:
Thread Number is 777Thread Number is 888Thread Number is 666
You might want to force the threads to print their thread numbers three times in a row, rather than having these messages interwoven with those from the other threads. To accomplish this, you need a mechanism that prevents two threads from executing the same code at the same time. In this way, each thread gets to write to the console other thread can run the same code.
The way to do this is through a device that is fundamental to parallel programming, the mutex. The term derives from the words mutual exclusion and it refers to the action of giving one thread exclusive access to code or a data item.
Using a mutex requires three simple steps, which have their exact equivalents in using a padlock: creating the mutex, like purchasing the padlock; using the mutex to guard an item, locking the padlock; and releasing the mutex, unlocking it. Let's look at how this is done in Windows.
First define a handle for the mutex, just as you did for a thread:
HANDLE hMutex;
You then call the function to create a mutex:
hMutex = CreateMutex ( NULL, // security parameters ...