Caffe2 - C++ API
A deep learning, cross platform ML framework
ThreadPool.h
1 #ifndef CAFFE2_UTILS_THREADPOOL_H_
2 #define CAFFE2_UTILS_THREADPOOL_H_
3 
4 #include "ThreadPoolCommon.h"
5 
6 #include <functional>
7 #include <memory>
8 #include <mutex>
9 #include <vector>
10 
11 //
12 // A work-stealing threadpool loosely based off of pthreadpool
13 //
14 
15 namespace caffe2 {
16 
17 struct Task;
18 class WorkersPool;
19 
20 constexpr size_t kCacheLineSize = 64;
21 
22 // A work-stealing threadpool with the given number of threads.
23 // NOTE: the kCacheLineSize alignment is present only for cache
24 // performance, and is not strictly enforced (for example, when
25 // the object is created on the heap). Thus, in order to avoid
26 // misaligned intrinsics, no SSE instructions shall be involved in
27 // the ThreadPool implemetation.
28 class alignas(kCacheLineSize) ThreadPool {
29  public:
30  static std::unique_ptr<ThreadPool> defaultThreadPool();
31  ThreadPool(int numThreads);
32  ~ThreadPool();
33  // Returns the number of threads currently in use
34  int getNumThreads() const;
35 
36  // Sets the minimum work size (range) for which to invoke the
37  // threadpool; work sizes smaller than this will just be run on the
38  // main (calling) thread
39  void setMinWorkSize(size_t size);
40  size_t getMinWorkSize() const { return minWorkSize_; }
41  void run(const std::function<void(int, size_t)>& fn, size_t range);
42 
43  // Run an arbitrary function in a thread-safe manner accessing the Workers
44  // Pool
45  void withPool(const std::function<void(WorkersPool*)>& fn);
46 
47  private:
48  mutable std::mutex executionMutex_;
49  size_t minWorkSize_;
50  size_t numThreads_;
51  std::shared_ptr<WorkersPool> workersPool_;
52  std::vector<std::shared_ptr<Task>> tasks_;
53 };
54 
55 } // namespace caffe2
56 
57 #endif // CAFFE2_UTILS_THREADPOOL_H_
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...