Creating Threads
Example 1 creates a second thread of execution (main() is the first thread) and uses that thread to call a global function that prints the message “Hello World!” to the console.
Example 1 – Creating threads
#include <rw/thread/RWThreadFunction.h>
#include <iostream> // 1
 
using namespace std;
 
void hello(void) // 2
{
cout << "Hello World!” << endl;
}
 
int main()
{
RWThreadFunction myThread = RWThreadFunction::make(hello); // 3
myThread.start(); // 4
myThread.join(); // 5
return 0;
}
//1 Includes the header file containing the RWThreadFunction class declaration used in the example.
//2 Defines a global function to produce the message.
//3 Uses a Threading package global function to construct an RWThreadFunction runnable that executes the hello() function when started. That runnable object is bound to a local handle named myThread.
//4 Starts the runnable. This results in the creation of a new thread that then executes the hello() function.
//5 Waits for the newly created thread to finish execution.
The following sections take a closer look at some of the key components of this example.