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