proxygen
WorkerThread.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2015-present, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD-style license found in the
6  * LICENSE file in the root directory of this source tree. An additional grant
7  * of patent rights can be found in the PATENTS file in the same directory.
8  *
9  */
10 #pragma once
11 
12 #include <atomic>
13 #include <cstdint>
14 #include <folly/Portability.h>
16 #include <mutex>
17 #include <thread>
18 
19 namespace folly {
20 class EventBaseManager;
21 }
22 
23 namespace proxygen {
24 
29 class WorkerThread {
30  public:
31  explicit WorkerThread(
32  folly::EventBaseManager* ebm, const std::string& evbName = std::string());
33  virtual ~WorkerThread();
34 
40  void start();
41 
58  void stopWhenIdle();
59 
71  void forceStop();
72 
80  void wait();
81 
86  return &eventBase_;
87  }
88 
93  std::thread::native_handle_type getThreadNativeHandle() noexcept {
94  return thread_.native_handle();
95  }
96 
101  std::thread::id getThreadId() const noexcept {
102  return thread_.get_id();
103  }
104 
112  return currentWorker_;
113  }
114 
115  protected:
116  virtual void setup();
117  virtual void cleanup();
118 
119  private:
120  enum class State : uint8_t {
121  IDLE, // Not yet started
122  STARTING, // start() called, thread not fully started yet
123  RUNNING, // Thread running normally
124  STOP_WHEN_IDLE, // stopWhenIdle() called, not stopped yet
125  FORCE_STOP, // forceStop() called, but the loop is still cleaning up
126  };
127 
128  // Forbidden copy constructor and assignment operator
129  WorkerThread(WorkerThread const &) = delete;
130  WorkerThread& operator=(WorkerThread const &) = delete;
131 
132  void runLoop();
133 
134  State state_{State::IDLE};
135  std::thread thread_;
138  folly::EventBaseManager* eventBaseManager_{nullptr};
139 
140  // A thread-local pointer to the current WorkerThread for this thread
141  static FOLLY_TLS WorkerThread* currentWorker_;
142 };
143 
144 } // proxygen
static FOLLY_TLS WorkerThread * currentWorker_
Definition: WorkerThread.h:141
std::thread::native_handle_type getThreadNativeHandle() noexcept
Definition: WorkerThread.h:93
—— Concurrent Priority Queue Implementation ——
Definition: AtomicBitSet.h:29
requires E e noexcept(noexcept(s.error(std::move(e))))
folly::EventBase eventBase_
Definition: WorkerThread.h:137
std::thread::id getThreadId() const noexcept
Definition: WorkerThread.h:101
bool wait(Waiter *waiter, bool shouldSleep, Waiter *&next)
auto start
folly::EventBase * getEventBase()
Definition: WorkerThread.h:85
std::mutex mutex
const char * string
Definition: Conv.cpp:212
const
Definition: upload.py:398
static WorkerThread * getCurrentWorkerThread()
Definition: WorkerThread.h:111
void cleanup()
Definition: Init.cpp:59