Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a latest example of using mutex under boost 1.48.0?

Most of the examples I've found on the web are outdated, using boost::mutex which I've failed to declare either including or . Is there any clear example of how to use boost::mutex in ver 1.48.0? The tutorials in Chapter 27 (Threads) are extremely unclear and do not provide any code samples.

like image 926
derekhh Avatar asked Nov 17 '11 22:11

derekhh


1 Answers

Check this example (boost::mutex usage is presented in Resource::use()):

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

class Resource
{
public:
    Resource(): i(0) {}

    void use()
    {
        boost::mutex::scoped_lock lock(guard);
        ++i;
    }

private:
    int i;
    boost::mutex guard;
};

void thread_func(Resource& resource)
{
    resource.use();
}

int main()
{
    Resource resource;
    boost::thread_group thread_group;
    thread_group.create_thread(boost::bind(thread_func, boost::ref(resource)));
    thread_group.create_thread(boost::bind(thread_func, boost::ref(resource)));
    thread_group.join_all();
    return 0;
}
like image 154
Andriy Tylychko Avatar answered Nov 09 '22 07:11

Andriy Tylychko