如何使用Boost制作关键部分?

Vie*_*Vie 10 c++ multithreading synchronization boost critical-section

对于我的跨平台应用程序,我已经开始使用Boost,但我无法理解如何实现代码来重现Win32的关键部分或.Net的行为lock.

我想编写一个Foo可以从不同线程调用的方法来控制对共享字段的写操作.应该允许同一线程内的递归调用(Foo() - > Foo()).

在C#中,这个实现非常简单:

object _synch = new object();
void Foo()
{
    lock (_synch)  // one thread can't be lock by him self, but another threads must wait untill
    {
        // do some works
        if (...) 
        {
           Foo();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*sky 11

使用boost,您可以使用boost :: lock_guard <>类:

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;
};
Run Code Online (Sandbox Code Playgroud)

PS这些类位于Boost.Thread库中.