Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a critical section with Boost?

For my cross-platform application I have started to use Boost, but I can't understand how I can implement code to reproduce behavior of Win32's critical section or .Net's lock.

I want to write a method Foo that can be called from different threads to control write operations to shared fields. Recursive calls within the same thread should be allowed (Foo() -> Foo()).

In C# this implementation is very simple:

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();
        }
    }
}
like image 551
Vie Avatar asked Aug 15 '11 15:08

Vie


1 Answers

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.

like image 159
Alexander Verbitsky Avatar answered Sep 28 '22 19:09

Alexander Verbitsky