Pages

Hello boost::thread

I have just written a Makefile (for Linux-RedHat) and now I'm using it for a tiny program testing multithreading with Boost. The fact is that the standard C++ thread support in g++ is still marked as experimental, and I need something more stable - so I'm using boost::thread.

The idea is having a simple environment where writing a few functions using the boost::thread features. I'm not using a real test environment, at least for the moment, because we are still to take a few decisions on it. In any case it would be easy to move the job done in this way to actual test cases.

Here is the main, it just prints a message and calls the functions (currently just one):

#include
#include "hello.h"

int main(int argc, char* argv[])
{
std::cout << "Testing Boost " << std::endl;

mt01();

// std::cout << "Press Enter to terminate" << std::endl;
// std::cin.ignore();
}

I currently don't need the parameter list in main, but it could be useful for future tests, and it gives no harm.
Initially I thought it was a good idea to "pause" the execution at the end. But since I'm running my application directly from the terminal, I don't actually need to let it hang until I press enter, so I commented the last two lines.

The hello.h is currently just an include guard and a function declaration:

#ifndef THISTHREAD_HELLO_H
#define THISTHREAD_HELLO_H

extern void mt01();

#endif // THISTHREAD_HELLO_H

And here finally is the first test on boost::thread:

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

namespace
{
void hello() // 1.
{
std::cout << "Hello from thread "
<< boost::this_thread::get_id() << std::endl;
}
}

void mt01()
{
std::cout << "This is thread "
<< boost::this_thread::get_id() << std::endl; // 2.

boost::thread t(&hello); // 3.
t.join(); // 4.

std::cout << "Back to "
<< boost::this_thread::get_id() << std::endl;
}

1. Just a simple local function.
2. To show that actually we are in a different thread, I get the id of the current thread through the free function get_id() defined in the boost::this_thread namespace.
3. An object boost::thread is created passing to it the address of a function (1), that would be executed in a different thread.
4. The current thread hangs waiting the termination of the other one.

Actually, I have already written a very similar post almost an year ago. At that time I was testing boost::thread on Windows, for a different project. In this case, the striking similarity is a feature, since we can see that with boost::thread (and in a near future with the standard C++0x thread) we can achieve multithreading with the same code compiled on different environments.

No comments:

Post a Comment