-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThread.cpp
More file actions
54 lines (44 loc) · 1.36 KB
/
Thread.cpp
File metadata and controls
54 lines (44 loc) · 1.36 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
//
// Created by parallels on 2020/1/20.
//
#include <unistd.h>
#include "Thread.h"
Thread::Thread(Thread::func _func, std::string name) : func_(_func), name_(name), start_(0), join_(0), mutex_(), cond_(mutex_) {}
Thread::~Thread() {
if (start_ && !join_) pthread_detach(tid_);
}
//为了保存线程名字等信息,由于线程必须传入静态的函数,静态函数不属于对象所以对象无法保存信息
// ,在此另辟蹊径,使用一个单独struct集合保存必要信息
struct Data {
pthread_t *tid;
pid_t *pid;
std::function<void()> func;
std::string name;
Condition cond;
MutexLock mutex;
Data(pthread_t *tid, pid_t *pid, std::function<void()> func, std::string name) :
tid(tid), pid(pid), func(func), name(name), mutex(), cond(mutex)
{}
};
void *startThread(void *obj) {
Data *data = static_cast<Data*>(obj);
//data->cond.wait();
data->func();
}
void Thread::start() {
start_ = true;
Data *data = new Data(&tid_, &pid_, func_, name_);
if (pthread_create(&tid_, NULL, startThread, data)) {
start_ = false;
printf("thread : %lud start error\n", tid_);
delete data;
} else {
start_ = true;
//data->cond.notify();
printf("thread : %lud start success\n", tid_);
}
}
int Thread::join() {
join_ = true;
return pthread_join(pid_, NULL);
}