You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

msgqueuethread.h 1.6 kB

8 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #ifndef MSGQUEUETHREAD_H
  2. #define MSGQUEUETHREAD_H
  3. #include <mutex>
  4. #include <queue>
  5. #include <functional>
  6. #include <condition_variable>
  7. #include <thread>
  8. using namespace std;
  9. //TODO:实现移到cpp中
  10. template<class Msg>
  11. class MsgQueueThread
  12. {
  13. typedef function<void (shared_ptr<Msg>)> Handler;
  14. public:
  15. void setHandler(Handler handler)
  16. {
  17. mHandler = handler;
  18. }
  19. void start()
  20. {
  21. if (mRun)
  22. return;
  23. mRun=true;
  24. thread thd(&MsgQueueThread::loop, this);
  25. mThread.swap(thd);
  26. }
  27. void stop()
  28. {
  29. if (!mRun)
  30. return;
  31. mRun=false;
  32. unique_lock<mutex> lock(mQueueMutex);
  33. while(!mQueue.empty())
  34. mQueue.pop();
  35. mQueueCnd.notify_all();
  36. lock.unlock();
  37. mThread.join();
  38. }
  39. void sendMessage(shared_ptr<Msg> msg)
  40. {
  41. unique_lock<mutex> lock(mQueueMutex);
  42. mQueue.push(msg);
  43. mQueueCnd.notify_one();
  44. }
  45. private:
  46. void loop()
  47. {
  48. while (mRun) {
  49. unique_lock<mutex> lock(mQueueMutex);
  50. if (mQueue.empty())
  51. mQueueCnd.wait(lock);
  52. if (!mRun)
  53. return;
  54. auto msg = mQueue.front();
  55. mQueue.pop();
  56. lock.unlock();//队列已经没有利用价值了,放了它
  57. if (mHandler)
  58. mHandler(msg);
  59. }
  60. }
  61. private:
  62. condition_variable mQueueCnd;
  63. mutex mQueueMutex;
  64. queue<shared_ptr<Msg>> mQueue;
  65. bool mRun=false;
  66. Handler mHandler;
  67. thread mThread;
  68. };
  69. #endif // MSGQUEUETHREAD_H

mac下的“飞秋”大多数只是飞鸽传书协议,而且未发现令人满意的开源项目,所以基于c++与qt实现了基础的飞秋协议。

Contributors (1)