多線程 std::call_once 轉自:https://blog.csdn.net/hengyunabc/article/details/33031465 std::call_once的特點:即使有多個線程要訪問同一個函數,只有一個線程會成功。 std::call_once的用途:當某個數據只有 ...
多線程 std::call_once
轉自:https://blog.csdn.net/hengyunabc/article/details/33031465
std::call_once的特點:即使有多個線程要訪問同一個函數,只有一個線程會成功。
std::call_once的用途:當某個數據只有在初始化的時候需要線程安全的時候,使用std::once是最安全和恰當的做法。
註意:std::once_flag的生命周期一定要長於std::call_once的線程的聲明周期,所以一般把std::once_flag聲明為全局變數。
例子:
#include <iostream>
#include <thread>
#include <mutex>
std::once_flag flag;
void do_once()
{
std::call_once(flag, [](){ std::cout << "Called once" << std::endl; });
}
int main()
{
std::thread t1(do_once);
std::thread t2(do_once);
std::thread t3(do_once);
std::thread t4(do_once);
t1.join();
t2.join();
t3.join();
t4.join();
}
執行結果:do_once()函數只被調用了一次。