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

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;
};

Advertisements
This entry was posted in C++, Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s