我尝试运行文档页面https://en.cppreference.com/w/cpp/thread/call_once中的示例,但它无法按预期工作。它会无限卡住。我想知道为什么会出现这种情况,或者它是否只是与某些特定编译器版本相关的错误。这是我用来运行程序的https://repl.it/repls/UtterJubilantArchitects。
#include <iostream>
#include <thread>
#include <mutex>
std::once_flag flag1, flag2;
void simple_do_once()
{
std::call_once(flag1, [](){ std::cout << "Simple example: called once\n"; });
}
void may_throw_function(bool do_throw)
{
if (do_throw) {
std::cout << "throw: call_once will retry\n"; // this may appear more than once
throw std::exception();
}
std::cout << "Didn't throw, call_once will not attempt again\n"; // guaranteed once
}
void do_once(bool do_throw)
{
try {
std::call_once(flag2, may_throw_function, do_throw);
}
catch (...) {
}
}
int main()
{
std::thread st1(simple_do_once);
std::thread st2(simple_do_once);
std::thread st3(simple_do_once);
std::thread st4(simple_do_once);
st1.join();
st2.join();
st3.join();
st4.join();
std::thread t1(do_once, true);
std::thread t2(do_once, true);
std::thread t3(do_once, false);
std::thread t4(do_once, true);
t1.join();
t2.join();
t3.join();
t4.join();
}
__GLIBCXX__
宏进行验证)。 它在libc ++中不存在,例如https://wandbox.org/permlink/7rPCL57q8E55Eq6m。 请参见下面的答案以及我的评论。 - walnut