Веб-сайт самохостера Lotigara

summaryrefslogtreecommitdiff
path: root/source/core/StarWorkerPool.hpp
blob: 4d07aad1061a3556e58f0d2aba831c4902e4cb0b (plain)
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#pragma once

#include "StarThread.hpp"

namespace Star {

STAR_EXCEPTION(WorkerPoolException, StarException);

STAR_CLASS(WorkerPool);

// Shareable handle for a WorkerPool computation that does not produce any
// value.
class WorkerPoolHandle {
public:
  // Returns true if the work is completed (either due to error or actual
  // completion, will not re-throw)
  bool done() const;

  // Waits up to given millis for the computation to finish.  Returns true if
  // the computation finished within the allotted time, false otherwise.  If
  // the computation is finished but it threw an exception, it will be
  // re-thrown here.
  bool wait(unsigned millis) const;

  // synonym for wait(0)
  bool poll() const;

  // Wait until the computation finishes completely.  If the computation threw
  // an exception it will be re-thrown by this method.
  void finish() const;

private:
  friend WorkerPool;

  struct Impl {
    Impl();

    Mutex mutex;
    ConditionVariable condition;
    atomic<bool> done;
    std::exception_ptr exception;
  };

  WorkerPoolHandle(shared_ptr<Impl> impl);

  shared_ptr<Impl> m_impl;
};

// Shareable handle for a WorkerPool computation that produces a value.
template <typename ResultType>
class WorkerPoolPromise {
public:
  // Returns true if the work is completed (either due to error or actual
  // completion, will not re-throw)
  bool done() const;

  // Waits for the given amount of time for the work to be completed.  If the
  // work is completed, returns true.  If the producer function throws for any
  // reason, this method will re-throw the exception.  If millis is zero, does
  // not wait at all simply polls to see if the computation is finished.
  bool wait(unsigned millis) const;

  // synonym for wait(0)
  bool poll() const;

  // Blocks until the work is done, and returns the result.  May be called
  // multiple times to access the result.  If the computation threw
  // an exception it will be re-thrown by this method.
  ResultType& get();
  ResultType const& get() const;

private:
  friend WorkerPool;

  struct Impl {
    Mutex mutex;
    ConditionVariable condition;
    Maybe<ResultType> result;
    std::exception_ptr exception;
  };

  WorkerPoolPromise(shared_ptr<Impl> impl);

  shared_ptr<Impl> m_impl;
};

class WorkerPool {
public:
  // Creates a stopped pool
  WorkerPool(String name);
  // Creates a started pool
  WorkerPool(String name, unsigned threadCount);
  ~WorkerPool();

  WorkerPool(WorkerPool&&);
  WorkerPool& operator=(WorkerPool&&);

  // Start the thread pool with the given thread count range, or if it is
  // already started, reconfigure the thread counts.
  void start(unsigned threadCount);

  // Stop the thread pool, not necessarily finishing any pending jobs (may
  // leave pending jobs on the queue).
  void stop();

  // Try to finish any remaining jobs, then stop the thread pool.  This method
  // must not be called if the worker pool will continuously receive new work,
  // as it may not ever complete if that is the case.  The work queue must
  // eventually become empty for this to properly return.
  void finish();

  // Add the given work to the pool and return a handle for the work.  It not
  // required that the caller of this method hold on to the worker handle, the
  // work will be managed and completed regardless of the WorkerPoolHandle
  // lifetime.
  WorkerPoolHandle addWork(function<void()> work);

  // Like addWork, but the worker is expected to produce some result.  The
  // returned promise can be used to get this return value once the producer is
  // complete.
  template <typename ResultType>
  WorkerPoolPromise<ResultType> addProducer(function<ResultType()> producer);

private:
  class WorkerThread : public Thread {
  public:
    // Starts automatically
    WorkerThread(WorkerPool* parent);
    ~WorkerThread();

    void run() override;

    WorkerPool* parent;
    atomic<bool> shouldStop;
    atomic<bool> waiting;
  };

  void queueWork(function<void()> work);

  String m_name;
  Mutex m_threadMutex;
  List<unique_ptr<WorkerThread>> m_workerThreads;

  Mutex m_workMutex;
  ConditionVariable m_workCondition;
  Deque<function<void()>> m_pendingWork;
};

template <typename ResultType>
bool WorkerPoolPromise<ResultType>::done() const {
  MutexLocker locker(m_impl->mutex);
  return m_impl->result || m_impl->exception;
}

template <typename ResultType>
bool WorkerPoolPromise<ResultType>::wait(unsigned millis) const {
  MutexLocker locker(m_impl->mutex);

  if (!m_impl->result && !m_impl->exception && millis != 0)
    m_impl->condition.wait(m_impl->mutex, millis);

  if (m_impl->exception)
    std::rethrow_exception(m_impl->exception);

  if (m_impl->result)
    return true;

  return false;
}

template <typename ResultType>
bool WorkerPoolPromise<ResultType>::poll() const {
  return wait(0);
}

template <typename ResultType>
ResultType& WorkerPoolPromise<ResultType>::get() {
  MutexLocker locker(m_impl->mutex);

  if (!m_impl->result && !m_impl->exception)
    m_impl->condition.wait(m_impl->mutex);

  if (m_impl->exception)
    std::rethrow_exception(m_impl->exception);

  return *m_impl->result;
}

template <typename ResultType>
ResultType const& WorkerPoolPromise<ResultType>::get() const {
  return const_cast<WorkerPoolPromise*>(this)->get();
}

template <typename ResultType>
WorkerPoolPromise<ResultType>::WorkerPoolPromise(shared_ptr<Impl> impl)
  : m_impl(std::move(impl)) {}

template <typename ResultType>
WorkerPoolPromise<ResultType> WorkerPool::addProducer(function<ResultType()> producer) {
  // Construct a worker pool promise and wrap the producer to signal the
  // promise when finished.
  auto workerPoolPromiseImpl = make_shared<typename WorkerPoolPromise<ResultType>::Impl>();
  queueWork([workerPoolPromiseImpl, producer]() {
    try {
      auto result = producer();
      MutexLocker promiseLocker(workerPoolPromiseImpl->mutex);
      workerPoolPromiseImpl->result = std::move(result);
      workerPoolPromiseImpl->condition.broadcast();
    } catch (...) {
      MutexLocker promiseLocker(workerPoolPromiseImpl->mutex);
      workerPoolPromiseImpl->exception = std::current_exception();
      workerPoolPromiseImpl->condition.broadcast();
    }
  });

  return workerPoolPromiseImpl;
}

}