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 }