1 #include <list>
2
3 using namespace std;
4
5 class CYException
6 {
7 public:
8 CString sMsg;
9 int nError;
10 CYException(int nErr,char* sErrMsg){
11 nError = nErr;
12 sMsg = sErrMsg;
13 }
14 virtual ~CYException(){}
15
16 };
17
18 template <class T>
19 class CYQueueSyn
20 {
21 public:
22 std::list<T> queue;
23 int m_outtime;
24 HANDLE m_readSem;
25 HANDLE m_writeSem;
26 HANDLE m_synObject;
27 public:
28 CYQueueSyn(int length,int outtime = INFINITE);
29 virtual ~CYQueueSyn(void);
30 public:
31 void inq(T type);
32 T outq();
33
34 void free();
35 };
36 ////////////////////////////////////////////////////////
37 template<class T>
38 void CYQueueSyn<T>::free()
39 {
40 int size = (int)queue.size();
41 for(int i = 0; i<size; i++)
42 delete queue.back();
43 queue.clear();
44 }
45 template<class T>
46 CYQueueSyn<T>::CYQueueSyn(int length,int outtime)
47 {
48 m_readSem = CreateSemaphore(NULL,0,length,NULL);
49 m_writeSem = CreateSemaphore(NULL,length,length,NULL);
50 m_synObject = ::CreateMutex(NULL,false,NULL);
51
52 m_outtime = outtime;
53 }
54 template<class T>
55 CYQueueSyn<T>::~CYQueueSyn()
56 {
57 CloseHandle(m_readSem);
58 CloseHandle(m_writeSem);
59 CloseHandle(m_synObject);
60 }
61
62 template<class T>
63 void CYQueueSyn<T>::inq(T type) throw(CYException)
64 {
65 int rVal = WaitForSingleObject(m_writeSem,m_outtime);
66 if(rVal == WAIT_OBJECT_0)
67 {
68 if(WaitForSingleObject(m_synObject,INFINITE) == WAIT_OBJECT_0)
69 {
70 queue.push_back(type);
71 ReleaseMutex(m_synObject);
72 }
73 }
74 else if(rVal == WAIT_TIMEOUT)
75 {
76 throw CYException(1,"TIMEOUT");
77 }
78 else if(rVal == WAIT_ABANDONED)
79 {
80 throw CYException(-1, "ERROR");
81 }
82 ReleaseSemaphore(m_readSem,1,NULL);
83 }
84 template<class T>
85 T CYQueueSyn<T>::outq() throw(CYException)
86 {
87 T value;
88 int rVal = WaitForSingleObject(m_readSem,m_outtime);
89 if(rVal == WAIT_OBJECT_0)
90 {
91 if(WaitForSingleObject(m_synObject,INFINITE) == WAIT_OBJECT_0)
92 {
93 value = queue.front();
94 queue.pop_front();
95 ReleaseMutex(m_synObject);
96 }
97 }
98 else if(rVal == WAIT_TIMEOUT)
99 {
100 throw CYException(1,"TIMEOUT");
101 }
102 else if(rVal == WAIT_ABANDONED)
103 {
104 throw CYException(-1,"ERROR");
105 }
106
107 ReleaseSemaphore(m_writeSem,1,NULL);
108 return value;
109 }
110
111 #endif
如上,测试代码下载:http://www.pudn.com/downloads97/sourcecode/windows/other/109201257cqueue.rar