std::lock 我怎么知道它失败了
std::lock how do I know it failed
It is not clear from the documentation。此模板函数 returns 作废。该文件提到 -
If the function cannot lock all objects, the function first unlocks
all objects it successfully locked (if any) before failing.
但是调用者怎么知道失败了呢?
它会阻塞直到成功并且异常是唯一的失败场景吗?
It throws an error on any issue.
正如其他一些 SO 成员过去在我自己的问题上向我提到的那样,请远离 CPlusPlus.com - The Canonical Reference for Misinformation.
请借此机会了解 c and c++. C requires return codes or side-effects to function arguments, while C++ offers exceptions 除了上述之外的差异。
参数
(none)
Return 值
(none)
例外情况
Throws std::system_error when errors occur, including errors from the
underlying operating system that would prevent lock from meeting its
specifications. The mutex is not locked in the case of any exception
being thrown.
备注
lock() is usually not called directly: std::unique_lock and
std::lock_guard are used to manage exclusive locking.
例子
This example shows how lock and unlock can be used to protect shared
data.
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
int g_num = 0; // protected by g_num_mutex
std::mutex g_num_mutex;
void slow_increment(int id)
{
for (int i = 0; i < 3; ++i) {
g_num_mutex.lock();
++g_num;
std::cout << id << " => " << g_num << '\n';
g_num_mutex.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main()
{
std::thread t1(slow_increment, 0);
std::thread t2(slow_increment, 1);
t1.join();
t2.join();
}
It is not clear from the documentation。此模板函数 returns 作废。该文件提到 -
If the function cannot lock all objects, the function first unlocks all objects it successfully locked (if any) before failing.
但是调用者怎么知道失败了呢? 它会阻塞直到成功并且异常是唯一的失败场景吗?
It throws an error on any issue.
正如其他一些 SO 成员过去在我自己的问题上向我提到的那样,请远离 CPlusPlus.com - The Canonical Reference for Misinformation.
请借此机会了解 c and c++. C requires return codes or side-effects to function arguments, while C++ offers exceptions 除了上述之外的差异。
参数
(none)
Return 值
(none)
例外情况
Throws std::system_error when errors occur, including errors from the underlying operating system that would prevent lock from meeting its specifications. The mutex is not locked in the case of any exception being thrown.
备注
lock() is usually not called directly: std::unique_lock and std::lock_guard are used to manage exclusive locking.
例子
This example shows how lock and unlock can be used to protect shared data.
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
int g_num = 0; // protected by g_num_mutex
std::mutex g_num_mutex;
void slow_increment(int id)
{
for (int i = 0; i < 3; ++i) {
g_num_mutex.lock();
++g_num;
std::cout << id << " => " << g_num << '\n';
g_num_mutex.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main()
{
std::thread t1(slow_increment, 0);
std::thread t2(slow_increment, 1);
t1.join();
t2.join();
}