/************************************************************************/
/* 实现一个通用同步队列
使用链表实现队列 (先入先出)
使用信号量等待实现同步
/************************************************************************/
#pragma once
#include "lock.h"
#include
template
class Queue
{
public:
inline Queue()
{
bInit = true;
count = 0;
semaphore.Create(0xFFFF);
}
inline ~Queue()
{
Close();
}
inline void Close()
{
if(bInit) {
bInit = false;
semaphore.Release(1); //释放信号 让正在wait的就返回
semaphore.Close();
}
}
inline int getCount()
{
return count;
}
inline bool Push(Type* type)
{
if(!bInit)
return false;
criticalsection.Lock();
queueList.push_back(type);
count++;
criticalsection.Unlock();
semaphore.Release(1); //发出信号 让Pop可以操作了
return true;
}
inline Type* Pop()
{
semaphore.Wait(INFINITE); //等待Push的信号发来后才进行动作
if(bInit == false)
return 0;
criticalsection.Lock();
Type *type = *(queueList.begin()); //取出链表头
queueList.pop_front(); //从链表弹出
count--;
criticalsection.Unlock();
return type;
}
private:
bool bInit;
int count;
Semaphore semaphore;
CriticalSection criticalsection;
std::list queueList;
};
另外贴上其中用到的信号量和临界区的包装:
lock.h
//临界区
class CriticalSection
{
public:
inline CriticalSection()
{
InitializeCriticalSection(&m_sect);
}
inline ~CriticalSection()
{
DeleteCriticalSection(&m_sect);
}
inline void Lock()
{
EnterCriticalSection(&m_sect);
}
inline void Unlock()
{
LeaveCriticalSection(&m_sect);
}
inline BOOL TryLock()
{
return TryEnterCriticalSection(&m_sect);
}
private:
CRITICAL_SECTION m_sect;
};
//信号量
class Semaphore
{
public:
inline Semaphore()
{
m_hSem = NULL;
}
inline ~Semaphore()
{
Close();
}
inline BOOL Create(LONG lMaximumCount)
{
m_hSem = CreateSemaphore(NULL, 0, lMaximumCount, NULL);
return (m_hSem != NULL);
}
inline void Close()
{
if (m_hSem)
{
CloseHandle(m_hSem);
m_hSem = NULL;
}
}
inline BOOL Release(LONG lReleaseCount)
{
return ReleaseSemaphore(m_hSem, lReleaseCount, NULL);
}
inline DWORD Wait(DWORD dwMilliseconds)
{
return WaitForSingleObject(m_hSem, dwMilliseconds);
}
public:
HANDLE m_hSem;
};