Apollo  v5.5.0
Open source self driving car software
thread_worker.h
Go to the documentation of this file.
1 /******************************************************************************
2  * Copyright 2018 The Apollo Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *****************************************************************************/
16 #pragma once
17 
18 #include <condition_variable>
19 #include <memory>
20 #include <thread>
21 
22 namespace apollo {
23 namespace perception {
24 namespace lib {
25 
26 class ThreadWorker {
27  public:
28  ThreadWorker() = default;
30 
31  // bind a bool returned function, should be called before start
32  void Bind(const std::function<bool()> &func);
33 
34  // start the thread loopy running
35  void Start();
36 
37  // wake up the thread to do something
38  void WakeUp();
39 
40  // wait util the one time execution is done
41  void Join();
42 
43  // release the thread resources
44  void Release();
45 
46  private:
47  // the main function of thread
48  void Core();
49 
50  private:
51  std::unique_ptr<std::thread> thread_ptr_;
52  std::mutex mutex_;
53  std::condition_variable condition_;
54 
55  bool work_flag_ = false;
56  bool exit_flag_ = true;
57 
58  std::function<bool()> work_func_;
59 };
60 
61 } // namespace lib
62 } // namespace perception
63 } // namespace apollo
void Bind(const std::function< bool()> &func)
Definition: blob.h:72
~ThreadWorker()
Definition: thread_worker.h:29
Definition: thread_worker.h:26