Creating Two or More Threads that Access the Same Resources
In Example 1 in Creating Threads a single thread was created that printed a message to the console. The original thread and the newly created thread were not competing for any shared resources.
Example 25 shows how unwanted interference can occur between two or more threads accessing the same data or resources. In it, two threads simultaneously attempt to write messages to the console using standard C++ iostreams.
Example 25 – Interference between threads
#include <rw/rstream.h>
#include <rw/thread/rwtMakeThreadFunction.h>
 
void hello(void)
{
for(int i=0;i<100;i++) {
cout << "Hello ” << "World!” << endl;
}
}
 
int main()
{
// Construct two thread objects
RWThreadFunction myThread1 = rwMakeThreadFunction(hello);
RWThreadFunction myThread2 = rwMakeThreadFunction(hello);
// Start the threads
myThread1.start();
myThread2.start();
// Wait for the threads to finish
myThread1.join();
myThread2.join();
return 0;
}
The “Hello World!” message is intentionally broken into separate output operations for each word. When the code is executed on a system with time-slicing or multiple processors, the two new threads execute simultaneously and produce jumbled output similar to the following:
 
Hello World!
Hello World!
Hello World!
Hello Hello World! World!
 
Hello Hello World! World!
 
Hello Hello World! World!
 
.
.
.
The output from the two threads has become interleaved at the word level. The words themselves remain intact because a stream only allows one thread at a time to execute an output operation. In this example, however, a complete message requires three separate output operations. This sequence of operations is not protected from interference by other threads.
To eliminate undesirable interference, a mechanism is needed that prohibits one thread from attempting output while another thread is in the middle of its message output sequence. One such mechanism is called a mutex.