C++应用程序多线程中的锁定方法

Lock Method in C++ Application Multi-Thread

本文关键字:锁定 方法 应用程序 多线程 C++      更新时间:2023-10-16

有什么方法可以锁定多线程应用程序中的方法吗??

注意:访问MySQL数据库

致以最良好的问候。

boost scoped_lock是一种简单且防傻的方法。将锁绑定到这样的对象会在由于任何原因留下作用域时自动释放锁。(return,exceptions,…)编辑:还要注意c++11:std::lock_guard和std::mutex,如@Useless 所示

class Foo 
{
 public:
 void bar() 
 {
   // Will grab the resource or wait until free
   ::boost::mutex::scoped_lock lock(m_mutex); 
   //Critical section
   // No need to unlock the lock will do that itself.
 }
private:
boost::mutex m_mutex;

}

这个例子在这里找到http://developer-resource.blogspot.com/2009/01/boost-scoped-lock.html

如果您有C++11:

class Foo
{
    std::mutex bar_mutex;
public:
    void bar()
    {
        std::lock_guard guard(foo_mutex);
        // ... do your stuff here ...
    }
};

相当于Johan的Boost版本。

请注意,它们都会锁定每个实例的方法——如果您希望阻止所有Foo实例同时调用Foo::bar,则将互斥对象设为static