1 #include<iostream> 2 #include<thread> 3 #include<string> 4 #include<vector> 5 #include<list> 6 #include<mutex> 7 #include<unistd.h> 8 using namespace std; 9 10 //用成員函數作為線程函數的方法寫線程 11 //std::cout 是共享對象(輸出流),應該確保它不受多個線程的同時訪問; 12 class A 13 { 14 public: 15 //線程1:把收到的用戶消息放入到一個隊列 16 void inMsgRecvQueue() 17 { 18 int i; 19 while(1) 20 { 21 cin >> i; 22 //my_mutex.lock(); 23 cout << "已檢測到輸入命令: " << i << endl; 24 msgRecvQueue.push_back(i); 25 //my_mutex.unlock(); 26 } 27 } 28 bool noempty_or_not() 29 { 30 if (!msgRecvQueue.empty()) 31 { 32 return true; 33 } 34 return false; 35 } 36 void delete_first() 37 { 38 msgRecvQueue.pop_front(); 39 } 40 41 void delete_first_app() 42 { 43 waitcommand.pop_front(); 44 } 45 46 //線程2:取出隊列中的首元素. 47 void outMsgRecvQueue() 48 { 49 while(1) 50 { 51 bool result = noempty_or_not(); 52 53 if (result == true) 54 { my_mutex.lock(); 55 cout << "將用戶輸入的命令" << msgRecvQueue.front() << "加入到App隊列,執行用戶程序 Please waitting...." << endl; 56 waitcommand.push_back(msgRecvQueue.front()); 57 delete_first(); 58 my_mutex.unlock(); 59 App(waitcommand.front()); //根據命令代碼來執行應用程序,假設耗時巨大; 60 delete_first_app(); 61 //my_mutex.unlock(); 62 } 63 else 64 { 65 //cout << "目前消息隊列中為空!" << endl; 66 } 67 } 68 cout <<"end!" << endl; 69 } 70 71 // 應用程序 72 void App (int ass) 73 { 74 sleep(10); 75 cout << " Command: " << ass << "執行完畢" << endl; 76 } 77 78 private: 79 std::list<int> waitcommand; 80 std::list<int> msgRecvQueue; 81 std::mutex my_mutex; //這個鎖專門用於系統對waitcommand和msgRecvQueue的互斥修改; 82 }; 83 84 int main() 85 { 86 A myobja; 87 88 std::thread myOutMsgObj(&A::outMsgRecvQueue, &myobja); 89 std::thread myInMsgObj(&A::inMsgRecvQueue, &myobja); 90 myOutMsgObj.join(); 91 myInMsgObj.join(); 92 return 0; 93 }
