C++应用程序多线程中的锁定方法
Lock Method in C++ Application Multi-Thread
有什么方法可以锁定多线程应用程序中的方法吗??
注意:访问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
。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 在这种情况下,有什么正确的方法可以实现锁定吗?
- 当被调用方法使用调用方已锁定的同一锁时,如何避免死锁
- 从C 中的Mutex锁定代码中的函数返回的好方法
- C++与双重检查锁定的危险:变通方法
- 通过私有互斥锁锁定对象的最佳方法是什么
- C++应用程序多线程中的锁定方法
- 锁定多个 std::mutex 的最佳方法是什么?
- 锁定std::list的有效方法
- 为什么TMutex方法Acquire()不锁定互斥对象?
- c++跨方法锁定
- 有什么方法可以通过Qt锁定除一个表单外的所有表单吗
- 在Linux上锁定对单个进程内数据访问的最快方法
- 这是一个好方法来锁定一个每秒60次循环的循环吗?