0
点赞
收藏
分享

微信扫一扫

[c/c++] std::call_once


当我们希望某些代码只会被调用一次时,可以使用 std::call_once 来实现。

code

#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()
{
simple_do_once();
simple_do_once();
//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();
}

output

Simple example: called once

 

举报

相关推荐

std::call_once

【C++】std::vector

C++——std::String

c++ std::function

C++(11):std::move

c++ std::ref()和&

【C++】详解std::thread

C++:线程(std::thread)

0 条评论