forked from linyacool/WebServer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThread.cpp
More file actions
executable file
·110 lines (94 loc) · 2.46 KB
/
Copy pathThread.cpp
File metadata and controls
executable file
·110 lines (94 loc) · 2.46 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// @Author Lin Ya
// @Email [email protected]
#include "Thread.h"
#include <assert.h>
#include <errno.h>
#include <linux/unistd.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/prctl.h>
#include <sys/types.h>
#include <unistd.h>
#include <memory>
#include "CurrentThread.h"
#include <iostream>
using namespace std;
namespace CurrentThread {
__thread int t_cachedTid = 0;
__thread char t_tidString[32];
__thread int t_tidStringLength = 6;
__thread const char* t_threadName = "default";
}
pid_t gettid() { return static_cast<pid_t>(::syscall(SYS_gettid)); }
void CurrentThread::cacheTid() {
if (t_cachedTid == 0) {
t_cachedTid = gettid();
t_tidStringLength =
snprintf(t_tidString, sizeof t_tidString, "%5d ", t_cachedTid);
}
}
// 为了在线程中保留name,tid这些数据
struct ThreadData {
typedef Thread::ThreadFunc ThreadFunc;
ThreadFunc func_;
string name_;
pid_t* tid_;
CountDownLatch* latch_;
ThreadData(const ThreadFunc& func, const string& name, pid_t* tid,
CountDownLatch* latch)
: func_(func), name_(name), tid_(tid), latch_(latch) {}
void runInThread() {
*tid_ = CurrentThread::tid();
tid_ = NULL;
latch_->countDown();
latch_ = NULL;
CurrentThread::t_threadName = name_.empty() ? "Thread" : name_.c_str();
prctl(PR_SET_NAME, CurrentThread::t_threadName);
func_();
CurrentThread::t_threadName = "finished";
}
};
void* startThread(void* obj) {
ThreadData* data = static_cast<ThreadData*>(obj);
data->runInThread();
delete data;
return NULL;
}
Thread::Thread(const ThreadFunc& func, const string& n)
: started_(false),
joined_(false),
pthreadId_(0),
tid_(0),
func_(func),
name_(n),
latch_(1) {
setDefaultName();
}
Thread::~Thread() {
if (started_ && !joined_) pthread_detach(pthreadId_);
}
void Thread::setDefaultName() {
if (name_.empty()) {
char buf[32];
snprintf(buf, sizeof buf, "Thread");
name_ = buf;
}
}
void Thread::start() {
assert(!started_);
started_ = true;
ThreadData* data = new ThreadData(func_, name_, &tid_, &latch_);
if (pthread_create(&pthreadId_, NULL, &startThread, data)) {
started_ = false;
delete data;
} else {
latch_.wait();
assert(tid_ > 0);
}
}
int Thread::join() {
assert(started_);
assert(!joined_);
joined_ = true;
return pthread_join(pthreadId_, NULL);
}