-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread.cpp
102 lines (81 loc) · 1.54 KB
/
thread.cpp
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
//
// Created by csw on 2021/7/27.
//
#include "stdafx.h"
#include "thread.h"
struct Thread::_impl_t {
_impl_t(Thread* p) : m_flag(0), m_running(false), m_p(p), m_runable(nullptr) {}
typedef std::shared_ptr<std::thread> thread_ptr;
volatile int m_flag;
volatile bool m_running;
Thread* m_p;
Runable* m_runable;
thread_ptr m_thread;
std::mutex m_mutex;
int start(Runable *runable) {
std::unique_lock<std::mutex> lock(m_mutex);
if (m_thread) {
return 0;
}
int ret = m_p->on_start();
if (ret != 0) {
return ret;
}
m_flag = 1;
m_runable = runable;
m_thread = thread_ptr(new std::thread(std::bind(&_impl_t::run, this)));
return 0;
}
int stop() {
std::unique_lock<std::mutex> lock(m_mutex);
if (!m_thread) {
return 0;
}
m_flag = 0;
int ret = m_p->on_stop();
if (m_running && m_thread->joinable()) {
m_thread->join();
} else {
m_thread->detach();
}
m_thread.reset();
return ret;
}
bool running() {
return m_flag > 0;
}
int run() {
int ret = 0;
m_running = true;
if (m_runable) {
ret = m_runable->run();
} else {
ret = m_p->run();
}
m_running = false;
return ret;
}
};
Thread::Thread() : m_impl(nullptr) {
m_impl = new _impl_t(this);
}
Thread::~Thread() {
m_impl->stop();
delete m_impl;
m_impl = nullptr;
}
int Thread::start(Runable *runable) {
return m_impl->start(runable);
}
int Thread::stop() {
return m_impl->stop();
}
int Thread::on_start() {
return 0;
}
int Thread::on_stop() {
return 0;
}
bool Thread::running() {
return m_impl->running();
}