libtasks Documentation  1.6
queue.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2013-2014 ADTECH GmbH
3  * Licensed under MIT (https://github.com/adtechlabs/libtasks/blob/master/COPYING)
4  *
5  * Author: Andreas Pohl
6  */
7 
8 #ifndef _QUEUE_H_
9 #define _QUEUE_H_
10 
11 #include <tasks/tools/spinlock.h>
12 #include <mutex>
13 
14 namespace tasks {
15 namespace tools {
16 
17 #ifndef CACHE_LINE_SIZE
18 #define CACHE_LINE_SIZE 64
19 #endif
20 
21 /*
22  * A thread safe queue
23  *
24  * Thx Herb Sutter for this implementation!
25  */
26 template <typename T>
27 class queue {
28  public:
29  queue() : m_first(new node(T())), m_last(m_first) {}
30  ~queue() {
31  while (nullptr != m_first) {
32  node* n = m_first;
33  m_first = m_first->next;
34  delete n;
35  }
36  }
37 
38  bool pop(T& res) {
39  // No scope lock here to release the lock before deleting the
40  // old node
41  m_pop_lock.lock();
42  if (nullptr != m_first->next) {
43  node* old = m_first;
44  m_first = m_first->next;
45  // for big data types we should optimize here and move the real copy
46  // out of the critical section
47  res = m_first->val;
49  delete old;
50  return true;
51  }
53  return false;
54  }
55 
56  bool push(const T& v) {
57  node* n = new node(v);
58  std::lock_guard<spinlock> lock(m_push_lock);
59  m_last->next = n;
60  m_last = n;
61  return true;
62  }
63 
64  private:
65  struct node {
66  node(T v) : val(v), next(nullptr) {}
67  T val;
68  std::atomic<node*> next;
69  char pad[CACHE_LINE_SIZE - sizeof(T) - sizeof(std::atomic<node*>)];
70  };
71 
81 };
82 
83 } // tools
84 } // tasks
85 
86 #endif // _QUEUE_H_
node * m_first
Definition: queue.h:73
spinlock m_pop_lock
Definition: queue.h:75
char pad[CACHE_LINE_SIZE-sizeof(T)-sizeof(std::atomic< node * >)]
Definition: queue.h:69
char pad0[CACHE_LINE_SIZE]
Definition: queue.h:72
char pad1[CACHE_LINE_SIZE]
Definition: queue.h:74
char pad4[CACHE_LINE_SIZE]
Definition: queue.h:80
char pad3[CACHE_LINE_SIZE]
Definition: queue.h:78
std::atomic< node * > next
Definition: queue.h:68
bool push(const T &v)
Definition: queue.h:56
bool pop(T &res)
Definition: queue.h:38
spinlock m_push_lock
Definition: queue.h:79
char pad2[CACHE_LINE_SIZE]
Definition: queue.h:76
#define CACHE_LINE_SIZE
Definition: queue.h:18
node * m_last
Definition: queue.h:77