How to produce an interleaved output in a multithreaded program?

Article ID: 909
Last updated: 31 Jan, 2008
Article ID: 909
Last updated: 31 Jan, 2008
Revision: 1
Views: 3648
Posted: 23 Oct, 2001
by Dean J.
Updated: 31 Jan, 2008
by Dean J.
Problem


During Threads Module training to our customers we often encountered this question: "How can I produce an interleaved output with the following cout statement using Threads module classes?"

cout << "Hello " << "World" << endl;




Cause





Action


If there is a function hello() that just prints "hello" and "world" as separate strings and multiple threads execute this function at the same time, then we would expect the output to be jumbled with "hello" and "world" strings interleaved. However, it is very unlikely that you could see a jumbled output because of the extreme processor speeds. To interleave these output operations force a context switch between these two string outputs.

A way to force a context switch is to put a sleep call in between the cout statements to move the first thread out of the ready queue to the waiting queue. This will give a chance to the second thread to print the same string "hello" and hence the two threads create output "hello" "hello" simulating the jumbled output. Even injecting a context switch using a sleep statement is not guaranteed to create the desired mixed output. You may have to execute the "hello" << sleep(100) << "world" statement multiple times to achieve the results you're after. 

Below is a sample program that illustrates this issue; followed by a partial output of the program.

#include <iostream>

#include <rw/thread/RWThreadFunction.h>
#include <rw/thread/rwtMakeThreadFunction.h>

#include <rw/thread/RWRunnableSelf.h>


void hello(void)
{
 int x;
 
 for(x=0;x<100;++x)
 {
  cout << "Hello ";
  rwSleep(100);
  cout << "World" << endl;
  
 }
}

int main(int argc, char* argv[])
{
 RWThreadFunction myThread1 = rwtMakeThreadFunction(hello);
 RWThreadFunction myThread2 = rwtMakeThreadFunction(hello);
 myThread1.start();
 myThread2.start();
 myThread1.join();
 myThread2.join();

 return 0;
}

Output:
 
Hello World
Hello World
Hello World
Hello World
Hello WorldWorld
Hello
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello WorldWorld
Hello
Hello World
WorldHello
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello WorldWorld
Hello
Hello WorldWorld

This article was:   Helpful | Not helpful
Report an issue
Article ID: 909
Last updated: 31 Jan, 2008
Revision: 1
Views: 3648
Posted: 23 Oct, 2001 by Dean J.
Updated: 31 Jan, 2008 by Dean J.

Others in this category