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