具有Reset功能的多线程同步队列
前一段时间写了一个多线程同步队列,并且加入了Reset功能。可以保证线程读到的不会是不可识别的数据。自己自测过,不过还是不能保证没有bug:)
// -------------------------头文件:ThreadSafeQueue.h---------------------------//
#include <wtypes.h>
typedef struct _MsgItem // 8 bytes size
{
USHORT MsgID;
USHORT wParam; // 2 bytes
ULONG lParam; // 4 bytes
} MsgItem;
class CTreadSafeMsgQueue
{
private:
// 同步
int m_HeaderToWrite;
int m_TailToRead;
HANDLE m_S_Producer;
HANDLE m_S_Consumer;
HANDLE m_E_Queue;
// 初始化
BOOL m_bInitedOK;
// Reset
int m_WritingThreadNum; // 当前正在调用PostMsg,且已进入同步操作状态的线程数目
int m_ReadingThreadNum; // 当前正在调用GettMsg,且已进入同步操作状态的线程数目
BOOL m_bStop; // 正在Reset
// 消息缓冲区
int MAX_QUE_SIZE;
MsgItem *m_Queue;
// 非法消息类型
USHORT INVALID_MSG_TYPE;
// 常数
typedef enum { SLEEP_TIME = 20 };
public:
CTreadSafeMsgQueue(int QueSize = 64, USHORT InvalidMsgType = 0xFFFF);
~CTreadSafeMsgQueue();
BOOL Reset();
BOOL GetMsg(MsgItem &Msg, int WaitTime);
BOOL PostMsg(const MsgItem Msg, int WaitTime);
private:
CTreadSafeMsgQueue(const CTreadSafeMsgQueue*);
CTreadSafeMsgQueue(const CTreadSafeMsgQueue&);
const CTreadSafeMsgQueue& operator = (const CTreadSafeMsgQueue&);
};
本文地址:http://com.8s8s.com/it/it1224.htm