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
*****************************************************************************/
16
#include "
modules/perception/common/lib/thread/thread_worker.h
"
17
18
namespace
apollo
{
19
namespace
perception {
20
namespace
lib {
21
22
void
ThreadWorker::Bind
(
const
std::function<
bool
()> &func) {
23
work_func_ = func;
24
}
25
26
void
ThreadWorker::Start
() {
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
35
void
ThreadWorker::WakeUp
() {
36
{
37
std::lock_guard<std::mutex> lock(mutex_);
38
work_flag_ =
true
;
39
}
40
condition_.notify_one();
41
}
42
43
void
ThreadWorker::Join
() {
44
std::unique_lock<std::mutex> lock(mutex_);
45
condition_.wait(lock, [&]() {
return
!work_flag_; });
46
}
47
48
void
ThreadWorker::Release
() {
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
62
void
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
apollo::perception::lib::ThreadWorker::Bind
void Bind(const std::function< bool()> &func)
Definition
thread_worker.cc:22
apollo::perception::lib::ThreadWorker::Release
void Release()
Definition
thread_worker.cc:48
apollo::perception::lib::ThreadWorker::Join
void Join()
Definition
thread_worker.cc:43
apollo::perception::lib::ThreadWorker::WakeUp
void WakeUp()
Definition
thread_worker.cc:35
apollo::perception::lib::ThreadWorker::Start
void Start()
Definition
thread_worker.cc:26
apollo
class register implement
Definition
arena_queue.h:37
thread_worker.h
modules
perception
common
lib
thread
thread_worker.cc