How do I make a critical section with Boost?

前端 未结 2 706
礼貌的吻别
礼貌的吻别 2021-01-17 15:40

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

2条回答
  •  天命终不由人
    2021-01-17 16:17

    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 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.

提交回复
热议问题