Tervel  1.0.0
A collection of wait-free containers and algorithms.
lock_API.h
Go to the documentation of this file.
1 #ifndef COARSE_LOCK_BUFFER_H
2 #define COARSE_LOCK_BUFFER_H
3 
4 #include <atomic>
5 
6 template<class T>
7 class TestClass {
8  public:
9  TestClass(size_t capacity, size_t num_threads)
10  : capacity_(capacity)
12  , head_(0)
13  , tail_(0)
14  , queue_(new std::atomic<T>[capacity_]) {
15  pthread_mutex_init(&queue_lock_, NULL);
16  for (size_t i = 0; i < capacity_; i++) {
17  queue_[i].store(reinterpret_cast<T>(nullptr));
18  }
19  };
20 
21  char * name() {
22  return "Coarse Lock";
23  }
24 
25  void attach_thread() {}
26 
27  void detach_thread() {}
28 
29  bool enqueue(T val) {
30  pthread_mutex_lock(&queue_lock_);
31  bool res = false;
32  if (!isFull()) {
33  queue_[fetchHeadSeq() & size_mask_] = val;
34  res = true;
35  }
36 
37  pthread_mutex_unlock(&queue_lock_);
38  return res;
39  }
40 
41  bool dequeue(T &val) {
42  pthread_mutex_lock(&queue_lock_);
43  bool res = false;
44  if (!isEmpty()) {
45  val = queue_[fetchTailSeq() & size_mask_];
46  res = true;
47  }
48 
49  pthread_mutex_unlock(&queue_lock_);
50 
51  return res;
52  }
53 
54  private:
55  uint64_t fetchHeadSeq() {
56  return head_++;
57  }
58 
59  uint64_t fetchTailSeq() {
60  return tail_++;
61  }
62 
63  bool isFull() {
64  return (tail_ == head_+capacity_);
65  }
66 
67  bool isEmpty() {
68  return (head_ == tail_);
69  }
70 
71  uint64_t capacity_;
72  uint64_t size_mask_;
73  uint64_t head_;
74  uint64_t tail_;
75 
76  std::atomic<T> *queue_;
77 
78  pthread_mutex_t queue_lock_;
79 };
80 
81 #endif // COARSE_LOCK_BUFFER_H
uint64_t capacity_
Definition: lock_API.h:71
void detach_thread()
Definition: lock_API.h:27
std::atomic< T > * queue_
Definition: lock_API.h:76
bool isFull()
Definition: lock_API.h:63
STL namespace.
bool isEmpty()
Definition: lock_API.h:67
pthread_mutex_t queue_lock_
Definition: lock_API.h:78
TestClass(size_t capacity, size_t num_threads)
Definition: lock_API.h:9
bool dequeue(T &val)
Definition: lock_API.h:41
bool enqueue(T val)
Definition: lock_API.h:29
void attach_thread()
Definition: lock_API.h:25
uint64_t head_
Definition: lock_API.h:73
Definition: blank_api.h:31
uint64_t fetchHeadSeq()
Definition: lock_API.h:55
uint64_t size_mask_
Definition: lock_API.h:72
char * name()
Definition: lock_API.h:21
uint64_t fetchTailSeq()
Definition: lock_API.h:59
uint64_t tail_
Definition: lock_API.h:74