DUNE-DAQ
DUNE Trigger and Data Acquisition software
Loading...
Searching...
No Matches
ReusableThread.hpp
Go to the documentation of this file.
1
11#ifndef UTILITIES_INCLUDE_UTILITIES_REUSABLETHREAD_HPP_
12#define UTILITIES_INCLUDE_UTILITIES_REUSABLETHREAD_HPP_
13
14#include <atomic>
15#include <chrono>
16#include <condition_variable>
17#include <functional>
18#include <mutex>
19#include <string>
20#include <thread>
21
22namespace dunedaq::utilities {
23
25{
26public:
27 explicit ReusableThread(int threadid = 0);
28
30
31 ReusableThread(const ReusableThread&) = delete;
35
36 // Set thread ID
37 void set_thread_id(int tid) { m_thread_id = tid; }
38
39 // Get thread ID
40 int get_thread_id() const { return m_thread_id; }
41
42 // Set name for pthread handle
43 void set_name(const std::string& name, int tid);
44
45 // Pin thread to CPU
46 void set_pin(int cpuid);
47
48 // Check for completed task execution
49 bool get_readiness() const { return m_task_executed; }
50
51 // Set task to be executed
52 template<typename Function, typename... Args>
53 bool set_work(Function&& f, Args&&... args)
54 {
55 if (!m_task_assigned && m_task_executed.exchange(false)) {
56 m_task = std::bind(f, args...); // NOLINT
57 m_task_assigned = true;
58 m_cv.notify_all();
59 return true;
60 }
61 return false;
62 }
63
64private:
65 // Internals
67 std::atomic<bool> m_task_executed;
68 std::atomic<bool> m_task_assigned;
69 std::atomic<bool> m_thread_quit;
70 std::atomic<bool> m_worker_done;
71 std::atomic<bool> m_named;
72 std::function<void()> m_task;
73
74 // Locks
75 std::mutex m_mtx;
76 std::condition_variable m_cv;
77 std::thread m_thread;
78
79 // Actual worker thread
80 void thread_worker();
81};
82
83} // namespace dunedaq::utilities
84
85#endif // UTILITIES_INCLUDE_UTILITIES_REUSABLETHREAD_HPP_
bool set_work(Function &&f, Args &&... args)
ReusableThread & operator=(const ReusableThread &)=delete
ReusableThread is not copy-assginable.
ReusableThread(const ReusableThread &)=delete
ReusableThread is not copy-constructible.
void set_name(const std::string &name, int tid)
ReusableThread & operator=(ReusableThread &&)=delete
ReusableThread is not move-assignable.
ReusableThread(ReusableThread &&)=delete
ReusableThread is not move-constructible.