-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcqueue.cpp
executable file
·86 lines (69 loc) · 2.06 KB
/
cqueue.cpp
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
#include "cqueue.h"
#include <iostream>
#include <cstdlib>
#include <cstdint>
#include <unistd.h>
#include <cstring>
using namespace std;
namespace collections
{
// lock free single reade, single writer
///////////////////////////////////////////
CQueueLockFreeSingle::CQueueLockFreeSingle( uint64_t a_ulQueueItemCount, uint64_t a_ulDataSize ) :
m_ulQueueSize( a_ulQueueItemCount ),
m_ulDataSize ( a_ulDataSize ),
m_ulMask ( a_ulQueueItemCount-1 )
{
m_nPageSize = getpagesize();
if( 0 != posix_memalign( &m_pQueue, m_nPageSize, m_ulQueueSize*m_ulDataSize ) )
{
cerr << "failed to get queue memory" << endl;
m_pQueue = nullptr;
}
}
CQueueLockFreeSingle::~CQueueLockFreeSingle()
{
if( nullptr != m_pQueue )
{
free( m_pQueue );
m_pQueue = nullptr;
}
}
/**
* @brief push at the tail
*
* @param a_pData
* @return bool
**/
bool CQueueLockFreeSingle::push( void* a_pData )
{
// full if head = tail+#elements
// not full then head < tail + #elements
// want to wait if full !(head == tail + elements) or head != tail + #elements
if( (m_ulTail + m_ulQueueSize) == m_ulHead )
{
return false;
}
// datasize is m_ulDataSize
// cast void as char, thus an int32 would have a size of 4 in x86
memcpy( ( static_cast<char*>(m_pQueue) + ( m_ulHead++ & m_ulMask )*m_ulDataSize), a_pData, m_ulDataSize );
return true;
}
/**
* @brief pop at the tail
*
* @return void*
**/
bool CQueueLockFreeSingle::pop( void* a_pData )
{
// empty if head == tail
// wait if empty !(head == tail) or head != tail
if( m_ulTail == m_ulHead )
{
// empty
return false;
}
memcpy( a_pData, ( static_cast<char*>(m_pQueue) + (m_ulTail++ & m_ulMask)*m_ulDataSize), m_ulDataSize );
return true;
}
}