C++多线程-chap1多线程入门7


这里,只是记录自己的学习笔记。

顺便和大家分享多线程的基础知识。然后从入门到实战。有代码。

知识点来源:

https://edu.51cto.com/course/26869.html


多线程调用函数,但函数只进入一次

使用 C++11 的 call_once 函数

 1 #include 
 2 #include 
 3 #include <string>
 4 #include 
 5 using namespace std;
 6 
 7 //多线程调用函数,但函数只进入一次
 8 
 9 void SystemInit() {
10     cout << "Call SystemInit " << endl;
11 }
12 
13 
14 
15 void SystemInitOne() {
16     static std::once_flag flag;
17     std::call_once(flag, SystemInit);
18 }
19 
20 
21 int main(int argc, char* argv[]) {
22     SystemInitOne();
23     SystemInitOne();
24 
25     for (int i = 0; i < 3; i++) {
26         thread th(SystemInitOne);
27         th.detach();
28     }
29 
30     getchar();
31     return 0;
32 }