1 #ifndef LOCKFREE_QUEUE_H
2 #define LOCKFREE_QUEUE_H
4 #include <boost/noncopyable.hpp>
11 template<class Tvalue>
12 class lockfree_queue : protected boost::noncopyable
17 node_type() : value(NULL) {}
19 mutable volatile size_t counter;
20 volatile size_t headloc;
21 volatile size_t tailloc;
23 volatile node_type *node;
24 const size_t element_num;
27 explicit lockfree_queue(size_t num = 65535) : counter(0), element_num(num) {
28 node = new node_type[element_num];
29 headloc = tailloc = 0;
38 bool push(const Tvalue *value) {
39 size_t tail, nexttail;
44 nexttail = get_num_next(tail);
45 if (unlikely(node[tail].value)) {
47 //do spin case of full queue
50 if (likely(__sync_bool_compare_and_swap(&tailloc, tail, nexttail))) break;
53 node[tail].value = const_cast<Tvalue *>(value);
54 __sync_add_and_fetch(&counter, 1);
60 size_t head, nexthead;
65 nexthead = get_num_next(head);
66 if (unlikely(!(node[head].value))) {
67 if (unlikely(headloc == tailloc)) {
72 if (likely(__sync_bool_compare_and_swap(&headloc, head, nexthead))) {
73 rtnvalue = node[head].value;
79 __sync_sub_and_fetch(&counter, 1);
80 node[head].value = NULL;
95 //get next value head and tail cyclic over elemental number
96 size_t get_num_next(const size_t num) {
97 if (unlikely(num + 1 >= element_num)) {
107 #endif // LOCKFREE_QUEUE_H