forked from IArvin/common
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase_thread.cpp
More file actions
85 lines (78 loc) · 1.75 KB
/
Copy pathbase_thread.cpp
File metadata and controls
85 lines (78 loc) · 1.75 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
#include <iostream>
#include <chrono>
#include <string.h>
#include "base_thread.h"
#include <thread>
namespace shadow {
base_thread::base_thread(const char* name) {
strcpy(thread_name, name);
#ifndef _WIN32
pthread_attr_init(&attr_);
#endif
}
base_thread::~base_thread() {
#ifndef _WIN32
pthread_attr_destroy(&attr_);
#endif
thread_list_.clear();
}
bool base_thread::activate(size_t threads) {
std::lock_guard<std::mutex> lock(mutex_);
for (size_t i = 0; i < threads; i++) {
#ifdef _WIN32
unsigned int dwThreadID = 0;
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, run, this, 0, &dwThreadID);
if (hThread == 0) {
printf("can't create thread");
return false;
}
thread_list_.emplace_back(hThread);
#else
pthread_t tid;
int err = pthread_create(&tid, &attr_, run, this);
if (err != 0) {
printf("can't create thread: %s\n", strerror(err));
return false;
}
thread_list_.emplace_back(tid);
#endif
}
return true;
}
void base_thread::join() {
#ifndef _WIN32
std::lock_guard<std::mutex> g(mutex_);
for (auto& thread : thread_list_) {
pthread_join(thread, 0);
}
thread_list_.clear();
#endif
}
bool base_thread::kill_all()
{
std::lock_guard<std::mutex> g(mutex_);
for (auto& thread : thread_list_) {
#ifdef _WIN32
TerminateThread(thread, 0);
#else
pthread_cancel(thread);
#endif
}
thread_list_.clear();
return true;
}
#ifdef _WIN32
unsigned int base_thread::run(void* param) {
#else
void* base_thread::run(void* param) {
#endif
base_thread* pthis = reinterpret_cast<base_thread*>(param);
try {
pthis->thread_proc();
}
catch (...) {
std::cout << "thread_proc exception: " << "[" << std::this_thread::get_id() << "]" << pthis->thread_name << std::endl;
}
return 0;
}
}