-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThread.cpp
More file actions
68 lines (54 loc) · 1.28 KB
/
Copy pathThread.cpp
File metadata and controls
68 lines (54 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include "Thread.h"
#include "CurrentThread.h"
Thread::Thread(ThreadFunc func, const std::string& name)
: func_(std::move(func)),
started_(false),
joined_(false),
tid_(0),
name_(name) {
setDefaultName();
}
Thread::~Thread() {
if (started_ && !joined_) {
thread_->detach();
}
}
void Thread::start() {
started_ = true;
thread_ = std::unique_ptr<std::thread>(new std::thread([&](){
{
std::unique_lock<std::mutex> lock(mtx_);
tid_ = CurrentThread::tid();
cond_.notify_one();
}
// 确保start返回后,tid_已经初始化
func_();
})); // 会进行移动
{
std::unique_lock<std::mutex> lock(mtx_);
while(tid_ == 0) {
cond_.wait(lock);
}
}
}
void Thread::join() {
joined_ = true;
thread_->join();
}
bool Thread::started() const {
return started_;
}
pid_t Thread::tid() const {
return tid_;
}
const std::string& Thread::name() const {
return name_;
}
void Thread::setDefaultName() {
int num = ++numCreated_;
if (name_.empty()) { // 如果没有提供名字,则使用默认的名字
char buf[32] = {0};
snprintf(buf, sizeof(buf), "Thread%d", num);
name_ = buf;
}
}