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

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

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

知识点来源:

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


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

使用 C++11 的 call_once 函数

 1 #include <iostream>
 2 #include <thread>
 3 #include <string>
 4 #include <mutex>
 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 }

 

 

作者:小乌龟
【转载请注明出处,欢迎转载】 希望这篇文章能帮到你

 

原文地址:https://www.cnblogs.com/music-liang/p/15586965.html