-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocklessQueue.h
More file actions
67 lines (59 loc) · 1.49 KB
/
Copy pathLocklessQueue.h
File metadata and controls
67 lines (59 loc) · 1.49 KB
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
/**************************************************
Zlib Copyright 2015 Daniel "MonzUn" Bengtsson
***************************************************/
#pragma once
#include <atomic>
#include <memory/Alloc.h>
template <typename T>
class LocklessQueue
{
private:
struct Node
{
Node( T val ) : value( val ), next( nullptr ) {}
T value;
Node* next;
};
Node* first;
std::atomic<Node*> divider, last;
public:
LocklessQueue( )
{
first = divider = last = tNew( Node, T( ) ); // Dummy divider
}
~LocklessQueue( )
{
while ( first != nullptr ) // Loop trough the queue and delete all remaining items
{
Node* temp = first;
first = temp->next;
tDelete( temp );
}
}
void Produce( const T& t )
{
last.load( )->next = tNew( Node, t ); // Add the new node
last = last.load( )->next; // Last takes a step forward and thereby publishes the new node so that the consumers can use it
while ( first != divider ) // Trim away unused nodes
{
Node* temp = first;
first = first->next;
tDelete( temp );
}
}
bool Consume( T& result )
{
if ( divider.load( ) != last.load( ) ) // Check so that the queue isn't empty
{
result = divider.load( )->next->value; // Get the value of the next item in queue
divider = divider.load( )->next; // Signal that we took it by moving the divider one step forward
return true;
}
return false; // Report list empty
}
void Clear() // May not run alongside a thread that uses Consume()
{
T val;
while ( Consume( val ) );
}
};