Pages

boost::thread

It's quite easy to create a new thread in an application using the boost::thread library.

In its simpler form, we just pass a pointer to a free function to the constructor of a boost::thread object, and that's it. We just have to remember to call a join on the thread object to let the main thread pending on the newly created one.

Here is an example that shows how the thing works:

#include <boost/thread/thread.hpp>
#include <iostream>

using namespace std;

namespace
{
void hello()
{
cout << "This is the thread " << boost::this_thread::get_id() << endl;
}
}

void dd01()
{
cout << "We are currently in the thread " << boost::this_thread::get_id() << endl;
boost::thread t(&hello);
t.join();
cout << "Back to the thread " << boost::this_thread::get_id() << endl;
}

Not much more to say about this example. The boost::thread object is started in the function hello(), that just print its thread id - calling the function get_id(). The main thread waits for the other thread to complete - thanks to the call to join() - then terminates.

No comments:

Post a Comment