Faiss

- Main Page
- Namespaces
- Classes
- Files

- File List

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