用三个线程按顺序循环打印ABC三个字母

  • 有两种方法:semaphore信号量和mutex互斥锁。需要注意的是C++11已经没有semaphore。
    • C++ 并发编程(六):信号量(Semaphore) - 止于至善 - SegmentFault 思否
      • https://segmentfault.com/a/1190000006818772
  • 线程按顺序执行(迅雷笔试题) - CSDN博客
    • http://blog.csdn.net/mafuli007/article/details/8488534
  • mutex - C++ Reference
    • http://www.cplusplus.com/reference/mutex/mutex/
用三个线程按顺序循环打印ABC三个字母
文章图片
用三个线程按顺序循环打印ABC三个字母
文章图片
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

    推荐阅读