LibraryLink Utilities  3.0.1
Modern C++ wrapper over LibraryLink and WSTP
WorkStealingQueue.h
Go to the documentation of this file.
1 
6 #ifndef LLU_ASYNC_WORKSTEALINGQUEUE_H
7 #define LLU_ASYNC_WORKSTEALINGQUEUE_H
8 
9 #include <mutex>
10 
11 namespace LLU::Async {
12 
19  template<typename BaseQueue>
21  using DataType = typename BaseQueue::value_type;
22 
23  BaseQueue theQueue;
24  mutable std::mutex theMutex;
25 
26  public:
31  void push(DataType data) {
32  std::lock_guard<std::mutex> lock(theMutex);
33  theQueue.push_front(std::move(data));
34  }
35 
40  [[nodiscard]] bool empty() const {
41  std::lock_guard<std::mutex> lock(theMutex);
42  return theQueue.empty();
43  }
44 
50  [[nodiscard]] bool tryPop(DataType& res) {
51  std::lock_guard<std::mutex> lock(theMutex);
52  if (theQueue.empty()) {
53  return false;
54  }
55  res = std::move(theQueue.front());
56  theQueue.pop_front();
57  return true;
58  }
59 
65  [[nodiscard]] bool trySteal(DataType& res) {
66  std::lock_guard<std::mutex> lock(theMutex);
67  if (theQueue.empty()) {
68  return false;
69  }
70  res = std::move(theQueue.back());
71  theQueue.pop_back();
72  return true;
73  }
74  };
75 } // namespace LLU::Async
76 
77 #endif // LLU_ASYNC_WORKSTEALINGQUEUE_H
LLU::Async::WorkStealingQueue::tryPop
bool tryPop(DataType &res)
Try to pop a task from the beginning of the queue in a non-blocking way.
Definition: WorkStealingQueue.h:50
LLU::Async::WorkStealingQueue::empty
bool empty() const
Check if the queue is empty.
Definition: WorkStealingQueue.h:40
LLU::Async::WorkStealingQueue::push
void push(DataType data)
Push new element to the beginning of the queue.
Definition: WorkStealingQueue.h:31
LLU::Async::WorkStealingQueue::trySteal
bool trySteal(DataType &res)
Try to pop a task from the end of the queue (this is what we call "stealing") in a non-blocking way.
Definition: WorkStealingQueue.h:65
LLU::Async::WorkStealingQueue
Wrapper class around a queue, that provides the interface for work stealing.
Definition: WorkStealingQueue.h:20