DUNE-DAQ
DUNE Trigger and Data Acquisition software
Loading...
Searching...
No Matches
WorkerThread.cpp
Go to the documentation of this file.
1
15#include "utilities/Issues.hpp"
16
17#include <memory>
18#include <string>
19
20dunedaq::utilities::WorkerThread::WorkerThread(std::function<void(std::atomic<bool>&)> do_work)
21 : m_thread_running(false)
22 , m_working_thread(nullptr)
23 , m_do_work(do_work)
24{
25}
26
27void
29{
30 if (thread_running()) {
31 throw ThreadingIssue(ERS_HERE,
32 "Attempted to start working thread "
33 "when it is already running!");
34 }
35 m_thread_running = true;
36 m_working_thread = std::make_unique<std::jthread>([&] { m_do_work(std::ref(m_thread_running)); });
37 auto handle = m_working_thread->native_handle();
38 auto rc = pthread_setname_np(handle, name.c_str());
39 if (rc != 0) {
40 std::ostringstream s;
41 s << "The name " << name << " provided for the thread is too long.";
42 ers::warning(ThreadingIssue(ERS_HERE, s.str()));
43 }
44}
45
46void
48{
49 if (!thread_running()) {
50 throw ThreadingIssue(ERS_HERE,
51 "Attempted to stop working thread "
52 "when it is not running!");
53 }
54 m_thread_running = false;
55
56 if (m_working_thread->joinable()) {
57 try {
58 m_working_thread->join();
59 } catch (std::system_error const& e) {
60 throw ThreadingIssue(ERS_HERE, std::string("Error while joining thread, ") + e.what());
61 }
62 } else {
63 throw ThreadingIssue(ERS_HERE, "Thread not in joinable state during working thread stop!");
64 }
65}
#define ERS_HERE
void stop_working_thread()
Stop the working thread.
void start_working_thread(const std::string &name="noname")
Start the working thread (which executes the do_work() function)
WorkerThread(std::function< void(std::atomic< bool > &)> do_work)
WorkerThread Constructor.
void warning(const Issue &issue)
Definition ers.hpp:115