-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThread.cc
More file actions
59 lines (51 loc) · 1 KB
/
Copy pathThread.cc
File metadata and controls
59 lines (51 loc) · 1 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
#include "../include/Thread.h"
#include <stdio.h>
Thread::Thread(ThreadCallback &&cb)
: _thid(0)
, _isRunning(false)
, _cb(std::move(cb))//注册
{
}
Thread::~Thread()
{
if(_isRunning)
{
pthread_detach(_thid);
}
}
//start参数列表中隐含着指向对象本身的this
void Thread::start()
{
//threadFunc函数必须要写成一个静态成员函数,消除this的影响
int ret = pthread_create(&_thid, nullptr, threadFunc, this);
if(ret)
{
perror("pthread_create");
return;
}
_isRunning = true;
}
void Thread::stop()
{
if(_isRunning)
{
int ret = pthread_join(_thid, nullptr);
if(ret)
{
perror("pthread_join");
return;
}
_isRunning = false;
}
}
void *Thread::threadFunc(void *arg)
{
Thread *ph = static_cast<Thread *>(arg);
if(ph)
{
//执行回调函数
ph->_cb();//线程所做的任务
}
/* return nullptr; */
pthread_exit(nullptr);
}