blob: 0a2f573aadf20725cac621c41c55943d1cf6404c (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
|
/*******************************************************************************
* Copyright (C) ST-Ericsson SA 2011
* License terms: 3-clause BSD license
******************************************************************************/
#include <pthread.h>
#include <assert.h>
#include "Types.h"
#include "CEventObject.h"
#include "CSemaphore.h"
#include "CSemaphoreQueue.h"
CSemaphoreQueue::CSemaphoreQueue(unsigned int MaxCount) : m_MaximumCount(MaxCount)
{
m_pEventObject = new CEventObject();
m_pSemaphore = new CSemaphore();
m_ObjectCollection.Add(m_pEventObject);
m_ObjectCollection.Add(m_pSemaphore);
m_Queue = new void*[MaxCount];
m_CurrentHead = 0;
m_CurrentTail = 0;
m_CurrentCount = 0;
}
CSemaphoreQueue::~CSemaphoreQueue()
{
delete m_pEventObject;
delete m_pSemaphore;
delete[] m_Queue;
}
bool CSemaphoreQueue::AddTail(void *pObject)
{
bool result = false;
CLockCS LocalCSLock(m_CSLock);
AddToQueueTail(pObject);
result = m_pSemaphore->Release(1);
if (!result) {
// Error : use ::GetLastError for cause of error
RemoveFromQueueTail(); // Not really necessary but keep,
// everything's gone pear-shaped anyway
}
return result;
}
RemoveResult CSemaphoreQueue::RemoveHead(void **ppObject, size_t mSecTimeout)
{
CWaitableObject *pWaitableObject = m_ObjectCollection.Wait(mSecTimeout);
if (pWaitableObject == m_pEventObject) {
return REMOVE_CANCEL;
} else if (pWaitableObject == m_pSemaphore) {
CLockCS LocalCSLock(m_CSLock);
*ppObject = RemoveFromQueueHead(); // Remove pObject from pObjectQueue head
return REMOVE_SUCCESS;
} else if (NULL == pWaitableObject) {
return REMOVE_TIMEOUT;;
} else {
// Should never occur
assert(false);
return REMOVE_CANCEL;;
}
}
void CSemaphoreQueue::SignalEvent()
{
CEventObject *pEvent = m_pEventObject;
pEvent->SetEvent();
}
void CSemaphoreQueue::IncrementHead()
{
++m_CurrentHead;
if (m_CurrentHead == m_MaximumCount) {
m_CurrentHead = 0;
}
}
void CSemaphoreQueue::IncrementTail()
{
++m_CurrentTail;
if (m_CurrentTail == m_MaximumCount) {
m_CurrentTail = 0;
}
}
void CSemaphoreQueue::AddToQueueTail(void *pObject)
{
m_Queue[m_CurrentTail] = pObject;
IncrementTail();
}
void *CSemaphoreQueue::RemoveFromQueueHead()
{
void *Object;
Object = m_Queue[m_CurrentHead];
IncrementHead();
return Object;
}
// Next 2 functions not really necessary - for error case only
void CSemaphoreQueue::DecrementTail()
{
if (m_CurrentTail == 0) {
m_CurrentTail = m_MaximumCount - 1;
} else {
--m_CurrentTail;
}
}
void CSemaphoreQueue::RemoveFromQueueTail()
{
DecrementTail();
m_Queue[m_CurrentTail] = 0;
}
|