File size: 2,470 Bytes
23d354c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Original Author: Phillip Johnston
// Licensed under CC0 1.0 Universal
// Original source: https://github.com/embeddedartistry/embedded-resources/blob/master/examples/cpp/dispatch.cpp
// Original article: https://embeddedartistry.com/blog/2017/2/1/dispatch-queues?rq=dispatch
//
// Modified for OpenSTA to use C++20 non-spinning DynamicLatch for synchronization.

#pragma once

#include <atomic>
#include <cstddef>
#include <condition_variable>
#include <cstdint>
#include <functional>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>

namespace sta {

class DynamicLatch
{
public:
  explicit DynamicLatch(std::ptrdiff_t initial_count = 0) :
    count_(initial_count)
  {
  }

  // Delete copy/move constructors to prevent accidental slicing/copying of atomics
  DynamicLatch(const DynamicLatch&) = delete;
  DynamicLatch& operator=(const DynamicLatch&) = delete;

  // Increases the latch count (used when a new task is dispatched)
  void
  countUp()
  {
    count_.fetch_add(1, std::memory_order_release);
  }

  // Decreases the latch count and wakes waiting threads if it hits zero
  void
  countDown(std::ptrdiff_t n = 1)
  {
    if (count_.fetch_sub(n, std::memory_order_release) == n) {
      count_.notify_all();
    }
  }

  // Blocks until the count reaches zero
  void
  wait() const
  {
    std::ptrdiff_t current = count_.load(std::memory_order_acquire);
    while (current != 0) {
      count_.wait(current, std::memory_order_acquire);
      current = count_.load(std::memory_order_acquire);
    }
  }

private:
  mutable std::atomic<std::ptrdiff_t> count_{0};
};

class DispatchQueue
{
  using fp_t = std::function<void(int thread)>;

public:
  DispatchQueue(size_t thread_count);
  ~DispatchQueue();
  void setThreadCount(size_t thread_count);
  size_t getThreadCount() const;
  // Dispatch and copy.
  void dispatch(const fp_t& op);
  // Dispatch and move.
  void dispatch(fp_t&& op);
  void finishTasks();

  // Deleted operations
  DispatchQueue(const DispatchQueue& rhs) = delete;
  DispatchQueue& operator=(const DispatchQueue& rhs) = delete;
  DispatchQueue(DispatchQueue&& rhs) = delete;
  DispatchQueue& operator=(DispatchQueue&& rhs) = delete;

private:
  void dispatch_thread_handler(size_t i);
  void terminateThreads();

  std::mutex lock_;
  std::vector<std::thread> threads_;
  std::queue<fp_t> q_;
  std::condition_variable cv_;
  DynamicLatch pending_task_count_latch_;
  bool quit_ = false;
};

} // namespace sta