Interestingly, it is pretty simple to write a multithreaded application using the C++ thread support library:
#include <thread>
using namespace std;
thread instance ( thread_procedure )
The thread class was introduced in C++11. This function can be used to create a thread. The equivalent of this function is pthread_create in the POSIX pthread library.
|
Argument |
Comment |
|
thread_procedure |
Thread function pointer |
Now a bit about the argument that returns the thread ID in the following code:
this_thread::get_id ()
This function is equivalent to the pthread_self() function in the POSIX pthread library. Refer to the following code:
thread::join()
The join() function is used to block the caller thread or the main thread so it will wait until the thread that has joined completes its task. This is a non-static function, so it has to be invoked on a thread object.
Let's see how to use the preceding functions to write a simple multithreaded program based on C++. Refer to the following program:
#include <thread>
#include <iostream>
using namespace std;
void threadProc() {
for( int count=0; count<3; ++count ) {
cout << "Message => "
<< count
<< " from "
<< this_thread::get_id()
<< endl;
}
}
int main() {
thread thread1 ( threadProc );
thread thread2 ( threadProc );
thread thread3 ( threadProc );
thread1.join();
thread2.join();
thread3.join();
return 0;
}
The C++ version of the multithreaded program looks a lot simpler and cleaner than the C version.