-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThread.cpp
More file actions
121 lines (105 loc) · 2.38 KB
/
Thread.cpp
File metadata and controls
121 lines (105 loc) · 2.38 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
111
112
113
114
115
116
117
118
119
120
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)
#include <Thread.h>
#include <CurrentThread.h>
#include <Exception.h>
//#include <muduo/base/Logging.h>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <linux/unistd.h>
namespace CurrentThread
{
__thread int t_cachedTid = 0;
char ctest[10];
}
namespace detail
{
pid_t gettid()
{
return static_cast<pid_t>(::syscall(SYS_gettid));
}
}
void CurrentThread::cacheTidLocal()
{
if (t_cachedTid == 0)
{
t_cachedTid = detail::gettid();
//int n = snprintf(t_tidString, sizeof t_tidString, "%5d ", t_cachedTid);
//assert(n == 6); (void) n;
}
}
Thread::Thread(const ThreadFunc& func, const std::string& n)
: started_(false),
pthreadId_(0),
tid_(0),
func_(func),
name_(n)
{
// numCreated_.increment();
}
Thread::~Thread()
{
// no join
}
void Thread::start()
{
assert(!started_);
started_ = true;
errno = pthread_create(&pthreadId_, NULL, &startThread, this);
if (errno != 0)
{
printf("Thread::start pthread_create error\n");
//LOG_SYSFATAL << "Failed in pthread_create";
}
}
int Thread::join()
{
assert(started_);
return pthread_join(pthreadId_, NULL);
}
void* Thread::startThread(void* obj)
{
Thread* thread = static_cast<Thread*>(obj);
thread->runInThread();
return NULL;
}
void Thread::runInThread()
{
tid_ = CurrentThread::tid();
func_();
/* CurrentThread::t_threadName = name_.c_str();
try
{
func_();
CurrentThread::t_threadName = "finished";
}
catch (const Exception& ex)
{
CurrentThread::t_threadName = "crashed";
fprintf(stderr, "exception caught in Thread %s\n", name_.c_str());
fprintf(stderr, "reason: %s\n", ex.what());
fprintf(stderr, "stack trace: %s\n", ex.stackTrace());
abort();
}
catch (const std::exception& ex)
{
CurrentThread::t_threadName = "crashed";
fprintf(stderr, "exception caught in Thread %s\n", name_.c_str());
fprintf(stderr, "reason: %s\n", ex.what());
abort();
}
catch (...)
{
CurrentThread::t_threadName = "crashed";
fprintf(stderr, "unknown exception caught in Thread %s\n", name_.c_str());
throw; // rethrow
}
*/
}