-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathmsgqueuethread.h
More file actions
82 lines (69 loc) · 1.57 KB
/
msgqueuethread.h
File metadata and controls
82 lines (69 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#ifndef MSGQUEUETHREAD_H
#define MSGQUEUETHREAD_H
#include <mutex>
#include <queue>
#include <functional>
#include <condition_variable>
#include <thread>
using namespace std;
//TODO:实现移到cpp中
template<class Msg>
class MsgQueueThread
{
typedef function<void (shared_ptr<Msg>)> Handler;
public:
void setHandler(Handler handler)
{
mHandler = handler;
}
void start()
{
if (mRun)
return;
mRun=true;
thread thd(&MsgQueueThread::loop, this);
mThread.swap(thd);
}
void stop()
{
if (!mRun)
return;
mRun=false;
unique_lock<mutex> lock(mQueueMutex);
while(!mQueue.empty())
mQueue.pop();
mQueueCnd.notify_all();
lock.unlock();
mThread.join();
}
void sendMessage(shared_ptr<Msg> msg)
{
unique_lock<mutex> lock(mQueueMutex);
mQueue.push(msg);
mQueueCnd.notify_one();
}
private:
void loop()
{
while (mRun) {
unique_lock<mutex> lock(mQueueMutex);
if (mQueue.empty())
mQueueCnd.wait(lock);
if (!mRun)
return;
auto msg = mQueue.front();
mQueue.pop();
lock.unlock();//队列已经没有利用价值了,放了它
if (mHandler)
mHandler(msg);
}
}
private:
condition_variable mQueueCnd;
mutex mQueueMutex;
queue<shared_ptr<Msg>> mQueue;
bool mRun=false;
Handler mHandler;
thread mThread;
};
#endif // MSGQUEUETHREAD_H