8#ifndef _Belle2_PThread_hh
9#define _Belle2_PThread_hh
11#include <daq/slc/system/LogFile.h>
26 template<
class WORKER>
27 static void destroy(
void* arg)
29 WORKER* worker = (WORKER*)arg;
33 template<
class WORKER>
34 static void* create_destroy(
void* arg)
36 WORKER* worker = (WORKER*)arg;
37 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
38 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
39 pthread_cleanup_push(PThread::destroy<WORKER>, arg);
42 }
catch (
const std::exception& e) {
43 LogFile::fatal(e.what());
45 pthread_cleanup_pop(1);
48 template<
class WORKER>
49 static void* create(
void* arg)
51 WORKER* worker = (WORKER*)arg;
52 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
53 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
56 }
catch (
const std::exception& e) {
57 LogFile::fatal(e.what());
63 static void exit() { pthread_exit(NULL); }
67 template<
class WORKER>
68 PThread(WORKER* worker,
bool destroyed =
true,
bool detached =
true, [[maybe_unused]]
const std::string& thread_name =
"")
72 if (pthread_create(&m_th, NULL, PThread::create_destroy<WORKER>,
73 (
void*)worker) != 0) {
77 if (pthread_create(&m_th, NULL, PThread::create<WORKER>,
78 (
void*)worker) != 0) {
82#if (defined(__GLIBC__) && defined(__GNU_SOURCE) && __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 12)
83 if ((m_th != 0) && (thread_name !=
"")) {
85 if (pthread_setname_np(m_th, thread_name.c_str()) != 0) {
86 LogFile::info(
"Failed to set process name %d", m_th);
89 pthread_getname_np(m_th, comp_name, 16);
90 if (strcmp(thread_name.c_str(), comp_name) != 0) {
91 prctl(PR_SET_NAME, thread_name.c_str());
93 }
catch (
const std::exception& e) {
94 LogFile::error(e.what());
106 pthread_t id() {
return m_th; }
107 pthread_t get_id() {
return m_th; }
110 if (m_th == 0)
return false;
111 return ::pthread_kill(m_th, signo) == 0;
113 bool is_alive() {
return this->kill(0); }
116 if (m_th == 0)
return false;
117 return ::pthread_detach(m_th) == 0;
121 if (m_th == 0)
return false;
122 return ::pthread_join(m_th, NULL) == 0;
126 if (m_th == 0)
return false;
127 return ::pthread_cancel(m_th) == 0;
Abstract base class for different kinds of events.