Faiss
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
WorkerThread.h
1 /**
2  * Copyright (c) 2015-present, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD+Patents license found in the
6  * LICENSE file in the root directory of this source tree.
7  */
8 
9 
10 #pragma once
11 
12 #include <condition_variable>
13 #include <future>
14 #include <deque>
15 #include <thread>
16 
17 namespace faiss { namespace gpu {
18 
19 class WorkerThread {
20  public:
21  WorkerThread();
22 
23  /// Stops and waits for the worker thread to exit, flushing all
24  /// pending lambdas
25  ~WorkerThread();
26 
27  /// Request that the worker thread stop itself
28  void stop();
29 
30  /// Blocking waits in the current thread for the worker thread to
31  /// stop
32  void waitForThreadExit();
33 
34  /// Adds a lambda to run on the worker thread; returns a future that
35  /// can be used to block on its completion.
36  /// Future status is `true` if the lambda was run in the worker
37  /// thread; `false` if it was not run, because the worker thread is
38  /// exiting or has exited.
39  std::future<bool> add(std::function<void()> f);
40 
41  private:
42  void startThread();
43  void threadMain();
44  void threadLoop();
45 
46  /// Thread that all queued lambdas are run on
47  std::thread thread_;
48 
49  /// Mutex for the queue and exit status
50  std::mutex mutex_;
51 
52  /// Monitor for the exit status and the queue
53  std::condition_variable monitor_;
54 
55  /// Whether or not we want the thread to exit
56  bool wantStop_;
57 
58  /// Queue of pending lambdas to call
59  std::deque<std::pair<std::function<void()>, std::promise<bool>>> queue_;
60 };
61 
62 } } // namespace
void stop()
Request that the worker thread stop itself.
std::future< bool > add(std::function< void()> f)