【发布时间】:2012-01-27 15:10:32
【问题描述】:
有没有办法在多线程应用程序中锁定方法??
注意:访问 MySQL 数据库
最好的问候。
【问题讨论】:
-
谷歌“Critical Section”c++(其实这里有个链接:msdn.microsoft.com/en-us/library/windows/desktop/…)
标签: c++ sql concurrency synchronization
有没有办法在多线程应用程序中锁定方法??
注意:访问 MySQL 数据库
最好的问候。
【问题讨论】:
标签: c++ sql concurrency synchronization
boost scoped_lock 是一种简单且万无一失的方法。当由于任何原因离开范围时,将锁绑定到这样的对象会自动释放锁。 (返回,异常,...)编辑:还要注意 c++11:@Useless 告诉的 std::lock_guard 和 std::mutex
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。
【讨论】: