In the previous recipe, we saw how to safely access a common resource from different threads. But in that recipe, we were doing two system calls (in locking and unlocking mutex
) to just get the value from an integer:
{ // Critical section begin. boost::lock_guard<boost::mutex> lock(i_mutex); i_snapshot = ++ shared_i; } // Critical section end.
This looks lame and slow! Can we make the code from the previous recipe better?
Reading the first recipe is all you need to start with this one. Some basic knowledge of multithreading will be welcome.
Let's see how to improve our previous example:
- Now, we need different headers:
#include <cassert> #include <cstddef> #include <iostream> #include <boost/thread/thread.hpp> #include <boost/atomic.hpp>
- Changing the type of
shared_i
is required:
boost::atomic<int> shared_i(0);
- Remove all the
boost::lock_guard
variables:
void do_inc...