How do I make a critical section with Boost?

蓝咒 提交于 2019-12-01 15:37:50
Alexander Verbitsky

With boost you can use boost::lock_guard<> class:

class test
{
public:
 void testMethod()
 {
  // this section is not locked
  {
   boost::lock_guard<boost::recursive_mutex> lock(m_guard);
   // this section is locked
  }
  // this section is not locked
 }
private:
    boost::recursive_mutex m_guard;
};

PS These classes located in Boost.Thread library.

jalf

Here's a rewrite of your example, using Boost.Thread: I removed the comments, but otherwise, it should be a 1-to-1 rewrite.

boost::recursive_mutex mtx;

void Foo()
{
    boost::lock_guard<boost::recursive_mutex> lock(mtx);
    if (...) 
    {
       Foo();
    }
}

The documentation can be found here.

Note that Boost defines a number of different mutex types. Because your example shows the lock being taken recursively, we need to use at least boost::recursive_mutex.

There are also different types of locks. In particular, if you want a reader-writer lock (so that multiple readers can hold the lock simultaneously, as long as no writer has the lock), you can use boost::shared_lock instead of lock_guard.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!