异常时解锁互斥量
Unlock mutex on exception
mutex.lock();
try
{
foo(); // can throw exception
}
catch (...)
{
mutex.unlock();
throw;
}
mutex.unlock();
为了保证解锁,我必须在 catch 块和正常情况下调用 mutex.unlock()
。是否有任何选项可以避免重复?
谢谢
您正在寻找的是像 std::lock_guard
:
这样的互斥包装器
#include <mutex>
std::mutex _mutex;
void call_foo()
{
std::lock_guard<std::mutex> lock(_mutex);
try
{
foo(); // can throw exception
}
catch (...)
{
// the mutex is unlocked here...
throw;
}
// ... and here
}
当 lock
超出范围时,其析构函数解锁底层互斥体 _mutex
。
另请参阅 std::unique_lock
,此 class 提供了更多功能,但可能会增加一些开销。在这种情况下,astd::lock_guard
就足够了。
mutex.lock();
try
{
foo(); // can throw exception
}
catch (...)
{
mutex.unlock();
throw;
}
mutex.unlock();
为了保证解锁,我必须在 catch 块和正常情况下调用 mutex.unlock()
。是否有任何选项可以避免重复?
谢谢
您正在寻找的是像 std::lock_guard
:
#include <mutex>
std::mutex _mutex;
void call_foo()
{
std::lock_guard<std::mutex> lock(_mutex);
try
{
foo(); // can throw exception
}
catch (...)
{
// the mutex is unlocked here...
throw;
}
// ... and here
}
当 lock
超出范围时,其析构函数解锁底层互斥体 _mutex
。
另请参阅 std::unique_lock
,此 class 提供了更多功能,但可能会增加一些开销。在这种情况下,astd::lock_guard
就足够了。