-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThread.cc
More file actions
61 lines (53 loc) · 1.29 KB
/
Copy pathThread.cc
File metadata and controls
61 lines (53 loc) · 1.29 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
#include "Thread.h"
#include "CurrentThread.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(); // thread 类 提供的 设置 分离线程的方法
}
}
void Thread::start() // 一个 Thread 对象 记录的就是 一个新线程的详细信息
{
started_ = true;
sem_t sem;
sem_init(&sem,false,0);
/////////// 子线程 ////////////
// 开启 线程 one loop poll thread
thread_ = std::shared_ptr<std::thread>(new std::thread([&](){
// 获取线程的 TID
tid_ = CurrentThread::tid();
sem_post(&sem);
// 开启一个新线程
func_();
}));
// 等待 获取上面创建新线程的 tid 值
sem_wait(&sem);
// started_ = false;
}
void Thread::join()
{
joined_ = true;
thread_->join();
}
void Thread::setDefaultName()
{
int num = ++numCreated_;
if(name_.empty())
{
char buffer[32] = {0};
snprintf(buffer,sizeof buffer , "Thread%d ",num);
name_ = buffer;
}
}