【发布时间】:2015-01-17 22:40:51
【问题描述】:
在后续链接 (http://www.cplusplus.com/reference/mutex/mutex/try_lock/) 上,我们声明样本只能返回 1 到 100000 之间的值。是否声明 0 不能在输出中?
// mutex::try_lock example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
volatile int counter (0); // non-atomic counter
std::mutex mtx; // locks access to counter
void attempt_10k_increases () {
for (int i=0; i<10000; ++i) {
if (mtx.try_lock()) { // only increase if currently not locked:
++counter;
mtx.unlock();
}
}
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(attempt_10k_increases);
for (auto& th : threads) th.join();
std::cout << counter << " successful increases of the counter.\n";
return 0;
}
无论如何,回答“如何获得 2?”很容易,但真的不清楚如何获得 1 而永远不会获得 0。
try_lock 可以“当没有其他线程对互斥锁拥有锁时虚假地失败,但在这种情况下重复调用会在某个时候成功”,但如果它是真的,那么 sample 可以返回 0(也可以在某些情况)。
但是,如果这个规范样本声明为真并且 0 不能在输出中,那么关于“虚假失败”的词可能不是真的吗?
【问题讨论】:
-
你会称 10000 个电话为“重复电话”吗?
-
啊,the joys of cplusplus.com。虽然如果你是迂腐的,该网站并没有声称 0 是不可能的。它只是声称 1-100000 是可能的。
-
我会说这是全球进步保证的边缘案例之一,很难从语言中正式化,但在某种程度上假设在任何合理的平台上,
try_lock的失败暗示 some 其他线程在某个时候取得了进展。 -
@kerrek-sb 为什么站点不声明 [0..100000] ?这是否意味着“虚假失败”可能会发生,但不会发生在单个第一个初始 try_lock 中?
-
@aefimov:我不知道网站为什么这么说,不是我写的。正如我所说,我认为不存在任何真正的硬件,其 0 是实际结果,但我也不认为标准可以保证这一点。
标签: c++