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