1 //  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 //  This source code is licensed under both the GPLv2 (found in the
3 //  COPYING file in the root directory) and Apache 2.0 License
4 //  (found in the LICENSE.Apache file in the root directory).
5 //
6 // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
7 // Use of this source code is governed by a BSD-style license that can be
8 // found in the LICENSE file. See the AUTHORS file for names of contributors.
9 #pragma once
10 
11 #include <functional>
12 
13 #include "rocksdb/rocksdb_namespace.h"
14 
15 namespace ROCKSDB_NAMESPACE {
16 
17 /*
18  * ThreadPool is a component that will spawn N background threads that will
19  * be used to execute scheduled work, The number of background threads could
20  * be modified by calling SetBackgroundThreads().
21  * */
22 class ThreadPool {
23  public:
~ThreadPool()24   virtual ~ThreadPool() {}
25 
26   // Wait for all threads to finish.
27   // Discard those threads that did not start
28   // executing
29   virtual void JoinAllThreads() = 0;
30 
31   // Set the number of background threads that will be executing the
32   // scheduled jobs.
33   virtual void SetBackgroundThreads(int num) = 0;
34   virtual int GetBackgroundThreads() = 0;
35 
36   // Get the number of jobs scheduled in the ThreadPool queue.
37   virtual unsigned int GetQueueLen() const = 0;
38 
39   // Waits for all jobs to complete those
40   // that already started running and those that did not
41   // start yet. This ensures that everything that was thrown
42   // on the TP runs even though
43   // we may not have specified enough threads for the amount
44   // of jobs
45   virtual void WaitForJobsAndJoinAllThreads() = 0;
46 
47   // Submit a fire and forget jobs
48   // This allows to submit the same job multiple times
49   virtual void SubmitJob(const std::function<void()>&) = 0;
50   // This moves the function in for efficiency
51   virtual void SubmitJob(std::function<void()>&&) = 0;
52 };
53 
54 // NewThreadPool() is a function that could be used to create a ThreadPool
55 // with `num_threads` background threads.
56 extern ThreadPool* NewThreadPool(int num_threads);
57 
58 }  // namespace ROCKSDB_NAMESPACE
59