fork download
  1. #include <iostream>
  2. #include <list>
  3. #include <thread>
  4. #include <mutex>
  5. #include <condition_variable>
  6.  
  7. using namespace std;
  8. //list element
  9. class myitem
  10. {
  11. public:
  12. myitem() { val = -1; };
  13. myitem(int n, int c){ val = n; chr = c; };
  14. int val;
  15. char chr;
  16. };
  17.  
  18. // mutex and condition variable to protect the list.
  19. std::mutex mymtx;
  20. condition_variable mycv;
  21. // the list to be protected
  22. std::list<myitem> mylist;
  23. // the atomic flag to test.
  24. std::atomic_flag testlk;
  25.  
  26. void datagenthread(char c)
  27. {
  28. int n = 10*1000*1000;
  29. while(n >0)
  30. {
  31. myitem item(n, c);
  32. {
  33. unique_lock<mutex> lk(mymtx); // get the lock
  34. if( testlk.test_and_set() != false) { // test the atomic flag
  35. cout<<"error in thread"<<c<<" for test lock"<<endl;
  36. }
  37. mylist.push_back(item);
  38. testlk.clear(); // clear the atomic before unlock.
  39. }
  40. mycv.notify_one();
  41. n--;
  42. }
  43. }
  44.  
  45. void datareadthread()
  46. {
  47. int count = 0;
  48. int readc = 0;
  49. while ( count <2) {
  50. {
  51. unique_lock<mutex> lk(mymtx); // acquire lock
  52. while ( mylist.size() <= 0) {
  53. mycv.wait(lk); // block until the thread get notified and get lock again.
  54. }
  55. if( testlk.test_and_set()!= false) {// test the atomic flag.
  56. cout<<"error in reader thread"<<endl;
  57. }
  58. myitem readitem;
  59. readitem = mylist.front();
  60. mylist.pop_front();
  61. readc++;
  62. if ( readitem.val == 1)
  63. {
  64. cout<<" get last one last item form a thread,"<<endl;
  65. count++;
  66. }
  67. testlk.clear(); // clear the atomic flag before unlock
  68. }//unique_lock destruct
  69. }//end while
  70. }
  71. int main()
  72. {
  73. std::thread cons( datareadthread);
  74. std::thread gen1( datagenthread, 'a');
  75. std::thread gen2( datagenthread, 'b');
  76. gen1.join();
  77. gen2.join();
  78. cons.join();
  79. cout << "all done\n";
  80. return 0;
  81. }
Success #stdin #stdout 2.81s 152448KB
stdin
Standard input is empty
stdout
 get last one last item form a thread,
 get last one last item form a thread,
all done