您正在寻找的是一个互斥包装器,如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
}
Run Code Online (Sandbox Code Playgroud)
当lock超出范围时,其析构函数会解锁基础互斥锁_mutex.
另请参见 std::unique_lock,此类提供了一些更多功能,可能会增加一些开销.在这种情况下,a std::lock_guard就足够了.
| 归档时间: |
|
| 查看次数: |
2643 次 |
| 最近记录: |