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