lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

[cpp]:  thread -- with header <syncstream>

 

 

 

 

一、说明:

 

  1、  【并发编程】thread编程中的同步输出:    std::osyncstream  //  Defined in header <syncstream>

 

 

 

二、程序代码

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 #include <thread>
 5 #include <syncstream>   //  std::osyncstream(); std::osyncstream(std::cout)
 6 
 7 
 8 int count = 0;
 9 
10 
11 void fun()
12 {
13     //  在多线程中,进行同步输出
14     std::osyncstream(std::cout) << "[os]#\tfun(" << ++count << ")" << std::endl ;
15 }
16 
17 
18 int main()
19 {
20     std::thread f1(fun) ;
21     std::thread f2(fun) ;
22     std::thread f3(fun) ;
23     std::thread f4(fun) ;
24     std::thread f5(fun) ;
25     
26     f1.join() ;
27     f2.join() ;
28     f3.join() ;
29     f4.join() ;
30     f5.join() ;
31     
32     return 0 ;
33 }

 

三、输出内容

1 g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
2 
3 
4 [os]#    fun(2)
5 [os]#    fun(1)
6 [os]#    fun(3)
7 [os]#    fun(4)
8 [os]#    fun(5)

 

四、参考资料

 

  1、  std::basic_osyncstream  --  https://en.cppreference.com/w/cpp/io/basic_osyncstream

 

posted on 2024-01-31 14:10  lnlidawei  阅读(7)  评论(0编辑  收藏  举报