C++ - Simple thread example of a string message processor

less than 1 minute read

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
class StringMessageProcessor
{
public:
	StringMessageProcessor()
	{
		m_exit = false;
		m_messageArrived = false;
	}
	~StringMessageProcessor()
	{
		m_thread.join();
	}
	void SetHandler(std::function<void(std::string const&)> msgHandler)
	{
		std::unique_lock<std::mutex> lock(m_condvarMutex);
		m_msgHandler = msgHandler;
	}
	void Start()
	{
		boost::thread thread([this] {
			while (!m_exit)
			{
				std::unique_lock<std::mutex> lock(m_condvarMutex);
				m_condvar.wait(lock, [this] { return m_exit || m_messageArrived;});
				if (!m_exit)
				{
                                     std::vector<Item> data;
                                     auto queueSize = m_msgQueue.size();
                                     while (m_msgQueue.size() > 0) {
                                         data.push_back(m_msgQueue.front());
                                         m_msgQueue.pop();
                                     }
                                     lock.unlock();
                                     for (auto const& msg: data) {
                                         m_processor->processItem(msg, queueSize);
                                     }
				}
			}
		});
		m_thread.swap(thread);
	}
	void Stop()
	{
		{
			std::lock_guard<std::mutex> lk(m_condvarMutex);
			m_exit = true;
		}
		m_condvar.notify_all();
	}
	bool PushMessage(std::string const& msg)
	{
		std::lock_guard<std::mutex> lk(m_condvarMutex);
		m_msgQueue.push(msg);
		m_messageArrived = true;
		m_condvar.notify_one();
		return true;
	}
private:
	boost::thread m_thread;
	std::mutex m_condvarMutex;
	std::condition_variable m_condvar;
	bool m_exit;
	bool m_messageArrived;
	std::queue<std::string> m_msgQueue;
	std::function<void(std::string const&)> m_msgHandler;
};