Apollo 11.0
自动驾驶开放平台
thread_worker.cc
浏览该文件的文档.
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 *****************************************************************************/
17
18namespace apollo {
19namespace perception {
20namespace lib {
21
22void ThreadWorker::Bind(const std::function<bool()> &func) {
23 work_func_ = func;
24}
25
27 if (thread_ptr_ == nullptr) {
28 thread_ptr_.reset(new std::thread(&ThreadWorker::Core, this));
29 }
30 std::lock_guard<std::mutex> lock(mutex_);
31 work_flag_ = false;
32 exit_flag_ = false;
33}
34
36 {
37 std::lock_guard<std::mutex> lock(mutex_);
38 work_flag_ = true;
39 }
40 condition_.notify_one();
41}
42
44 std::unique_lock<std::mutex> lock(mutex_);
45 condition_.wait(lock, [&]() { return !work_flag_; });
46}
47
49 if (thread_ptr_ == nullptr) {
50 return;
51 }
52 {
53 std::lock_guard<std::mutex> lock(mutex_);
54 work_flag_ = true;
55 exit_flag_ = true;
56 }
57 condition_.notify_one();
58 thread_ptr_->join();
59 thread_ptr_.reset(nullptr);
60}
61
62void ThreadWorker::Core() {
63 while (true) {
64 {
65 std::unique_lock<std::mutex> lock(mutex_);
66 condition_.wait(lock, [&]() { return work_flag_; });
67 }
68 if (exit_flag_) {
69 break;
70 }
71 work_func_();
72 {
73 std::lock_guard<std::mutex> lock(mutex_);
74 work_flag_ = false;
75 }
76 condition_.notify_one();
77 }
78}
79
80} // namespace lib
81} // namespace perception
82} // namespace apollo
void Bind(const std::function< bool()> &func)
class register implement
Definition arena_queue.h:37