用三个线程按顺序循环打印ABC三个字母
- 有两种方法:semaphore信号量和mutex互斥锁。需要注意的是C++11已经没有semaphore。
- C++ 并发编程(六):信号量(Semaphore) - 止于至善 - SegmentFault 思否
- https://segmentfault.com/a/1190000006818772
- C++ 并发编程(六):信号量(Semaphore) - 止于至善 - SegmentFault 思否
- 线程按顺序执行(迅雷笔试题) - CSDN博客
- http://blog.csdn.net/mafuli007/article/details/8488534
- mutex - C++ Reference
- http://www.cplusplus.com/reference/mutex/mutex/
文章图片
文章图片
1 // 2 //main.cpp 3 //LeetCode 4 // 5 //Created by Hao on 2017/3/16. 6 //Copyright ? 2017年 Hao. All rights reserved. 7 // 8 #include// std::cout 9 #include // std::thread, std::this_thread::sleep_for 10 #include // std::chrono::seconds 11 #include // std::mutex 12 13 std::mutex mtx; // mutex for critical section 14 int count = 0; 15 int num_count = 0; 16 17 void print_block_0 (int n) { 18// critical section (exclusive access to std::cout signaled by locking mtx): 19while (true) { 20if (count % 3 == 0) { 21mtx.lock(); 22 23++ count; 24 25std::cout << "A" << std::endl; 26 27mtx.unlock(); 28} 29 30if (num_count == 3) break; 31} 32 } 33 34 void print_block_1 (int n) { 35// critical section (exclusive access to std::cout signaled by locking mtx): 36while (true) { 37if (count % 3 == 1) { 38mtx.lock(); 39 40++ count; 41 42std::cout << "B" << std::endl; 43 44mtx.unlock(); 45} 46 47if (num_count == 3) break; 48} 49 } 50 51 void print_block_2 (int n) { 52// critical section (exclusive access to std::cout signaled by locking mtx): 53while (true) { 54if (count % 3 == 2) { 55mtx.lock(); 56 57++ num_count; // must be executed prior to the following statement, or else an extra "A" would be printed 58 59++ count; 60 61std::cout << "C" << std::endl; 62 63 //std::this_thread::sleep_for (std::chrono::seconds(1)); // sleep in case that an extra "A" is printed 64 65mtx.unlock(); 66} 67 68if (num_count == 3) break; 69} 70 } 71 72 int main() 73 { 74std::thread threads[3]; // default-constructed threads 75 76std::cout << "Spawning 3 threads...\n"; 77 78threads[0] = std::thread(print_block_0, 10); // move-assign threads 79threads[1] = std::thread(print_block_1, 10); // move-assign threads 80threads[2] = std::thread(print_block_2, 10); // move-assign threads 81 82std::cout << "Done spawning threads. Now waiting for them to join:\n"; 83for (int i=0; i<3; ++i) 84threads[i].join(); 85 86std::cout << "All threads joined!\n"; 87 88return 0; 89 }
View Code 【用三个线程按顺序循环打印ABC三个字母】
转载于:https://www.cnblogs.com/pegasus923/p/8575543.html
推荐阅读
- 放屁有这三个特征的,请注意啦!这说明你的身体毒素太多
- Docker应用:容器间通信与Mariadb数据库主从复制
- JS中的各种宽高度定义及其应用
- 由浅入深理解AOP
- 【译】20个更有效地使用谷歌搜索的技巧
- 涉毒患者(新诗)
- 参保人员因患病来不及到指定的医疗机构就医,能否报销医疗费用()
- mybatisplus如何在xml的连表查询中使用queryWrapper
- MybatisPlus|MybatisPlus LambdaQueryWrapper使用int默认值的坑及解决
- MybatisPlus使用queryWrapper如何实现复杂查询