Howto wait for multiple threads in C++

Whenever you have to deal with threads in C++ you should think of using the boost libraries which offer high end solutions for dealing with threads and creating thread-safe applications. A really nice feature on top of this are thread groups which allow you to manage multiple threads very easily. The following code snippet illustrates how to wait for multiple threads using such a thread group.

[sourcecode language=”cpp”]
#include <boost/thread.hpp>
#include <boost/thread.hpp>

void myFunc(int param)
{
std::cout << "Hello world" << std::endl;
}

int main()
{
int numberOfThreads==4;

boost::thread_group thread_group;

for(int counter = 0; counter < numberOfThreads;counter++)
thread_group.add_thread(new boost::thread(myFunc,5));

thread_group.join_all();

std::cout << "Done!" << std::endl;
}
[/sourcecode]

The code executes the function “myFunc” in a separate thread which is added to a thread group. This happens four times. The trick of executing the threads simultaneously is done by the join_all() command. The program waits until the last thread has finished and then is done. There is no magic about threads at all using boost. It is straight-forward and easy.

Leave a Reply

Your email address will not be published. Required fields are marked *