thread_supervisor
supervisor.cpp
Go to the documentation of this file.
1 /**
2  @file
3  @author Alexander Sherikov
4  @copyright 2022 Alexander Sherikov. Licensed under the Apache License,
5  Version 2.0. (see LICENSE or http://www.apache.org/licenses/LICENSE-2.0)
6  @brief
7 */
8 
9 
10 #define BOOST_TEST_MODULE thread_supervisor
11 #define BOOST_TEST_DYN_LINK
12 #include <boost/test/unit_test.hpp>
13 #include <boost/test/results_reporter.hpp>
14 #include <boost/timer/timer.hpp>
15 
16 
18 {
20  {
21  boost::unit_test::results_reporter::set_level(boost::unit_test::DETAILED_REPORT);
22  }
23  ~GlobalFixtureConfig() = default;
24 };
25 
26 
27 #pragma GCC diagnostic push
28 #pragma GCC diagnostic ignored "-Wpedantic"
29 // Depending on Boost version a compiler may issue a warning about extra ';',
30 // at the same time, compilation may fail on some systems if ';' is omitted.
32 #pragma GCC diagnostic pop
33 
34 
36 
37 
38 namespace
39 {
41  {
42  public:
43  std::atomic<std::size_t> counter_;
44 
45  public:
46  // cppcheck-suppress virtualCallInConstructor
47  void stopSupervisedThreads() override
48  {
49  getThreadSupervisor().stop();
50  }
51 
53  {
54  for (;;)
55  {
56  if (isThreadSupervisorInterrupted())
57  {
58  break;
59  }
60 
61  std::this_thread::sleep_for(std::chrono::seconds(1));
62  }
63  }
64 
66  {
67  ++counter_;
68  }
69 
71  {
72  counter_ = 0;
73  }
74 
76  {
77  stopSupervisedThreads();
78  }
79  };
80 } // namespace
81 
82 
83 
84 BOOST_AUTO_TEST_CASE(ThreadSupervisorStop)
85 {
86  TestThreadSupervisor pool;
87  pool.addSupervisedThread(tut::thread::Parameters(), &TestThreadSupervisor::threadFunction, &pool);
88  pool.addSupervisedThread(tut::thread::Parameters(), &TestThreadSupervisor::threadFunction, &pool);
89  pool.addSupervisedThread(tut::thread::Parameters(), &TestThreadSupervisor::threadFunction, &pool);
90 }
91 
92 
93 BOOST_AUTO_TEST_CASE(ThreadSupervisorCount)
94 {
95  TestThreadSupervisor pool;
96  BOOST_CHECK_EQUAL(pool.counter_, static_cast<std::size_t>(0));
97 
98  pool.addSupervisedThread(
100  tut::thread::Parameters::Restart(/*attempts=*/10, /*sleep_ms=*/5),
102  &TestThreadSupervisor::threadCounter,
103  &pool);
104 
105  std::this_thread::sleep_for(std::chrono::seconds(1));
106 
107  BOOST_CHECK_EQUAL(pool.counter_, static_cast<std::size_t>(10));
108  BOOST_CHECK(not pool.isThreadSupervisorInterrupted());
109 }
Inheritable supervisor simplifies starting class methods in separate threads.
Definition: supervisor.h:491
Restarting parameters.
Definition: supervisor.h:75
Thread parameters.
Definition: supervisor.h:56
~GlobalFixtureConfig()=default
BOOST_AUTO_TEST_CASE(ThreadSupervisorStop)
Definition: supervisor.cpp:84
BOOST_GLOBAL_FIXTURE(GlobalFixtureConfig)