forked from L1w-Y/muduo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThread.cc
More file actions
47 lines (43 loc) · 1.03 KB
/
Copy pathThread.cc
File metadata and controls
47 lines (43 loc) · 1.03 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
#include"Thread.h"
#include"CurrentThread.h"
#include"Poller.h"
#include"Logger.h"
#include<semaphore.h>
std::atomic<int> Thread::numCreated_{0};
Thread::Thread(ThreadFunc func,const std::string &name)
:started_(false),
joined_(false),
tid_(0),
func_(std::move(func)),
name_(name)
{
setDefaultName();
}
Thread::~Thread(){
if(started_ && !joined_){
thread_->detach();
}
}
void Thread::start(){
started_ = true;
sem_t sem;
sem_init(&sem,false,0);// 信号量初始化为 0
thread_ = std::make_shared<std::thread>([&](){
tid_ = CurrentThread::tid();// 在新线程中获取线程 ID
sem_post(&sem);// 通知主线程继续
if(func_)func_();// 执行线程的主要任务
});
sem_wait(&sem);// 主线程等待新线程完成初始化
}
void Thread::join(){
joined_=true;
thread_->join();
}
void Thread::setDefaultName(){
int num = ++numCreated_;
if(name_.empty()){
char buf[32]={};
snprintf(buf,sizeof buf,"thread %d", num);
name_=buf;
}
}