1 #ifndef _Belle2_PThread_hh
2 #define _Belle2_PThread_hh
4 #include <daq/slc/system/LogFile.h>
19 template<
class WORKER>
20 static void destroy(
void* arg)
22 WORKER* worker = (WORKER*)arg;
26 template<
class WORKER>
27 static void* create_destroy(
void* arg)
29 WORKER* worker = (WORKER*)arg;
30 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
31 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
32 pthread_cleanup_push(PThread::destroy<WORKER>, arg);
35 }
catch (
const std::exception& e) {
36 LogFile::fatal(e.what());
38 pthread_cleanup_pop(1);
41 template<
class WORKER>
42 static void* create(
void* arg)
44 WORKER* worker = (WORKER*)arg;
45 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
46 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
49 }
catch (
const std::exception& e) {
50 LogFile::fatal(e.what());
56 static void exit() { pthread_exit(NULL); }
60 template<
class WORKER>
61 PThread(WORKER* worker,
bool destroyed =
true,
bool detached =
true, std::string thread_name =
"")
65 if (pthread_create(&m_th, NULL, PThread::create_destroy<WORKER>,
66 (
void*)worker) != 0) {
70 if (pthread_create(&m_th, NULL, PThread::create<WORKER>,
71 (
void*)worker) != 0) {
75 #if (defined(__GLIBC__) && defined(__GNU_SOURCE) && __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 12)
76 if ((m_th != 0) && (thread_name !=
"")) {
78 if (pthread_setname_np(m_th, thread_name.c_str()) != 0) {
79 LogFile::info(
"Failed to set process name %d", m_th);
82 pthread_getname_np(m_th, comp_name, 16);
83 if (strcmp(thread_name.c_str(), comp_name) != 0) {
84 prctl(PR_SET_NAME, thread_name.c_str());
86 }
catch (
const std::exception& e) {
87 LogFile::error(e.what());
99 pthread_t id() {
return m_th; }
100 pthread_t get_id() {
return m_th; }
103 if (m_th == 0)
return false;
104 return ::pthread_kill(m_th, signo) == 0;
106 bool is_alive() {
return this->kill(0); }
109 if (m_th == 0)
return false;
110 return ::pthread_detach(m_th) == 0;
114 if (m_th == 0)
return false;
115 return ::pthread_join(m_th, NULL) == 0;
119 if (m_th == 0)
return false;
120 return ::pthread_cancel(m_th) == 0;