Using a Basic Mutex Mechanism
By using the RWMutexLock class, the hello() function can be modified, as in Example 26, so that each “Hello World!” message is produced without interference.
Example 26 – Avoiding interference between threads
void hello(void)
{
// Declare a static mutex instance that will
// be shared by all threads calling this function
static RWMutexLock mutex;
 
for(int i=0;i<100;i++) {
 
// Acquire mutex to block other threads
mutex.acquire();
 
cout << "Hello” << "World!” << endl;
 
// Release the mutex so other threads can say "hello”
mutex.release();
}
}
By adding synchronization, the code now produces the desired output. Each message appears without being interleaved with the messages produced by the other thread:
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
.
.