Turi Create  4.0
PosixTaskQueue.hpp
1 /* Copyright © 2020 Apple Inc. All rights reserved.
2  *
3  * Use of this source code is governed by a BSD-3-clause license that can
4  * be found in the LICENSE.txt file or at
5  * https://opensource.org/licenses/BSD-3-Clause
6  */
7 
8 #pragma once
9 
10 #include <core/parallel/thread_pool.hpp>
11 #include <ml/neural_net/TaskQueue.hpp>
12 
13 namespace turi {
14 namespace neural_net {
15 
16 /// Abstract implementation of TaskQueue that wraps turi::thread_pool
17 class PosixTaskQueue : public TaskQueue {
18  public:
19  static std::shared_ptr<PosixTaskQueue> GetGlobalConcurrentQueue();
20  static std::unique_ptr<PosixTaskQueue> CreateSerialQueue(const char* label);
21 
22  void DispatchAsync(std::function<void()> task) override;
23  void DispatchSync(std::function<void()> task) override;
24 
25  protected:
26  virtual thread_pool& GetThreadPool() = 0;
27 };
28 
29 /// Concrete implementation of PosixTaskQueue that owns a private thread_pool
30 /// instance.
32  public:
33  explicit SerialPosixTaskQueue(size_t num_threads);
34  ~SerialPosixTaskQueue() override;
35 
36  // Not copyable or movable.
39  SerialPosixTaskQueue& operator=(const SerialPosixTaskQueue&) = delete;
40  SerialPosixTaskQueue& operator=(SerialPosixTaskQueue&&) = delete;
41 
42  void DispatchApply(size_t n, std::function<void(size_t i)> task) override;
43 
44  protected:
45  thread_pool& GetThreadPool() override;
46 
47  private:
48  thread_pool threads_;
49 };
50 
51 /// Concrete implementation of PosixTaskQueue that wraps the global singleton
52 /// thread_pool.
54  public:
56  ~GlobalPosixTaskQueue() override;
57 
58  // Copyable or movable (but what's the point?)
61  GlobalPosixTaskQueue& operator=(const GlobalPosixTaskQueue&);
63 
64  void DispatchApply(size_t n, std::function<void(size_t i)> task) override;
65 
66  protected:
67  thread_pool& GetThreadPool() override;
68 };
69 
70 } // namespace neural_net
71 } // namespace turi
void DispatchAsync(std::function< void()> task) override
Abstract implementation of TaskQueue that wraps turi::thread_pool.
void DispatchSync(std::function< void()> task) override
Abstract task queue interface modeled after Grand Central Dispatch.
Definition: TaskQueue.hpp:17
virtual void DispatchApply(size_t n, std::function< void(size_t i)> task)=0