DUNE-DAQ
DUNE Trigger and Data Acquisition software
Loading...
Searching...
No Matches
ReusableThread.cpp
Go to the documentation of this file.
1
13#include "utilities/WorkerThread.hpp" // contains exception definition
14
15
17 : m_thread_id(threadid)
18 , m_task_executed(true)
19 , m_task_assigned(false)
20 , m_thread_quit(false)
21 , m_worker_done(false)
22 , m_thread(&ReusableThread::thread_worker, this)
23{}
24
26{
27 while (m_task_assigned) {
28 std::this_thread::sleep_for(std::chrono::milliseconds(1));
29 }
30 m_thread_quit = true;
31 while (!m_worker_done) {
32 std::this_thread::sleep_for(std::chrono::milliseconds(1));
33 m_cv.notify_all();
34 }
35 m_thread.join();
36}
37
38void
39dunedaq::utilities::ReusableThread::set_name(const std::string& name, int tid)
40{
41 set_thread_id(tid);
42 char tname[16];
43 snprintf(tname, 16, "%s-%d", name.c_str(), tid); // NOLINT
44 auto handle = m_thread.native_handle();
45 pthread_setname_np(handle, tname);
46
47 m_named = true;
48}
49
50void
52{
53 // Require that the thread has been named
54 if (!m_named) {
55 ers::warning( ThreadingIssue( ERS_HERE, "May not set CPU affinity for un-named thread" ) );
56 }
57
58 auto handle = m_thread.native_handle();
59 cpu_set_t cpuset;
60 CPU_ZERO(&cpuset);
61 CPU_SET(cpuid, &cpuset);
62 int rc = pthread_setaffinity_np(handle, sizeof(cpu_set_t), &cpuset);
63
64 if (rc != 0) {
65 ers::warning( ThreadingIssue( ERS_HERE, "Error calling pthread_setaffinity_np: " + std::to_string( rc ) ) );
66 }
67}
68
69void
71{
72 std::unique_lock<std::mutex> lock(m_mtx);
73
74 while (!m_thread_quit) {
75 if (!m_task_executed && m_task_assigned) {
76 m_task();
77 m_task_executed = true;
78 m_task_assigned = false;
79 } else {
80 m_cv.wait(lock);
81 }
82 }
83
84 m_worker_done = true;
85}
#define ERS_HERE
void set_name(const std::string &name, int tid)
void warning(const Issue &issue)
Definition ers.hpp:115