Saturday, January 17, 2009

C++ Multithread concurrent programming

Boost is my favorite choice and I suggest you to read the code of BOOST_THREAD class because it is very instructive. In version 1.36/37 there are some improvements. Here, I report the ones I like the most

1. You can create a thread and pass arguments to it (internally it uses boost::bind) as in
int k;
void thread_function (int i, std::string s, int& j);
boost::thread t(thread_function, 10,"hello world", boost::ref(k));

Note that this is making a copy of the function, so any reference should be passed via boost::ref().

2. You can have a multiple-readers/one-writer lock which is useful in many situations, just have a look to shared_mutex class. Another useful features is boost::mutex::scoped_lock (which was already available in previous versions). It implements the RAII concept and therefore when the lock variable is out-of-scope, it is automatically unlocked.

3. You can try to lock up to five resources and if one of them is locked all the others are released. This is useful to avoid deadlocks. Have a look to try_lock()

4. Interruptions for threads

Other improvements are described here. Here you find a code that uses a number of these features.

No comments:

Post a Comment