消息队列 By ivan.L 发表于 2018-01-04 本文是自己工作中写的一个WIN32版本消息队列,这里留存做一个记录。 操作系统: 64位win7 编译器: vs2013 1. 消息队列 #ifndef _MESSAGEQUEUE_H_INCLUDED_ #define _MESSAGEQUEUE_H_INCLUDED_ #include "stdafx.h" #include <Windows.h> #include <queue> /* * 描述: 用于实现一个线程安全的消息队列 * * 注: MessageQueue当前并不支持指针类型,对于指针类型,后续需要进行偏特化 */ template<typename T> class MessageQueue当前并不支持指针类型{ public: MessageQueue当前并不支持指针类型(int limit){ this->limit = limit; this->bStop = false; ::InitializeCriticalSection(&queueCs); ::InitializeConditionVariable(&queueNotEmpty); } ~MessageQueue当前并不支持指针类型(){ bStop = true; ::WakeConditionVariable(&queueNotEmpty); DeleteCriticalSection(&queueCs); } bool Push(T &msg){ bool result = true; ::EnterCriticalSection(&queueCs); if (msg_queue.size() >= limit){ result = false; } else{ if (msg_queue.empty()){ msg_queue.push(msg); ::WakeConditionVariable(&queueNotEmpty); } else{ msg_queue.push(msg); } } ::LeaveCriticalSection(&queueCs); return result; } T Pop(){ EnterCriticalSection(&queueCs); while (!bStop && msg_queue.empty()){ ::SleepConditionVariableCS(&queueNotEmpty, &queueCs, INFINITE); } if (!msg_queue.empty()){ T t = msg_queue.front(); msg_queue.pop(); LeaveCriticalSection(&queueCs); return t; } LeaveCriticalSection(&queueCs); return T(); } T Pop(DWORD dwMilliseconds){ EnterCriticalSection(&queueCs); if (msg_queue.empty()){ ::SleepConditionVariableCS(&queueNotEmpty, &queueCs, dwMilliseconds); } if (!msg_queue.empty()){ T t = msg_queue.front(); msg_queue.pop(); LeaveCriticalSection(&queueCs); return t; } LeaveCriticalSection(&queueCs); return T(); } int GetLimit()const{ return limit; } int GetCurrentSize(){ int sz; EnterCriticalSection(&queueCs); sz = msg_queue.size(); LeaveCriticalSection(&queueCs); return sz; } /* * 说明:很多时候我们可能并不需要很精确的获取到当前队列中的元素个数,因此我们可以不加锁进行保护(非线程安全) */ int GetCurrentSize_unsafe(){ return msg_queue.size(); } private: std::queue<T> msg_queue; size_t limit; bool bStop; CRITICAL_SECTION queueCs; CONDITION_VARIABLE queueNotEmpty; }; #endif [参看]: