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

C++ C+中的锁定方法+;应用程序多线程,c++,sql,concurrency,synchronization,C++,Sql,Concurrency,Synchronization,有没有办法在多线程应用程序中锁定方法 注意:要访问MySQL数据库 致以最诚挚的问候。增强作用域锁定是一种简单且不易出错的方法。如果将锁绑定到这样的对象,则无论出于何种原因,只要留下作用域,就会自动释放锁。(返回,异常,…)编辑:另请注意c++11:std::lock_-guard和std::mutex,如@unavouse所述 class Foo { public: void bar() { // Will grab the resource or wait until fre

有没有办法在多线程应用程序中锁定方法

注意:要访问MySQL数据库


致以最诚挚的问候。

增强作用域锁定是一种简单且不易出错的方法。如果将锁绑定到这样的对象,则无论出于何种原因,只要留下作用域,就会自动释放锁。(返回,异常,…)编辑:另请注意c++11:std::lock_-guard和std::mutex,如@unavouse所述

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;
}

这个例子就是在这里找到的 如果您有C++11:

class Foo
{
    std::mutex bar_mutex;
public:
    void bar()
    {
        std::lock_guard guard(foo_mutex);

        // ... do your stuff here ...
    }
};
相当于Johan的Boost版本

注意,他们都锁定每个实例的方法-如果你希望所有FO实例都被阻止调用<代码> Fo::Bar < /Cuth>,请同时使用MutX <代码>静态<代码>。< /P>谷歌“临界段”C++(实际上,这里是一个链接:)