我试图从文档页面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()
{ …
Run Code Online (Sandbox Code Playgroud)