SLProject  4.2.000
A platform independent 3D computer graphics framework for desktop OS, Android, iOS and online in web browsers
AsyncWorker.cpp
Go to the documentation of this file.
1 /**
2  * \file AsyncWorker.cpp
3  * \brief Implementation of an async worker thread
4  * \date May 2024
5  * \authors Marino von Wattenwyl
6  * \copyright http://opensource.org/licenses/GPL-3.0
7  * \remarks Please use clangformat to format the code. See more code style on
8  * https://github.com/cpvrlab/SLProject4/wiki/SLProject-Coding-Style
9 */
10 
11 #include <AsyncWorker.h>
12 #include <Utils.h>
13 
14 //-----------------------------------------------------------------------------
16 {
17  stop();
18 }
19 //-----------------------------------------------------------------------------
21 {
22  _ready = false;
23  _thread = std::thread(&AsyncWorker::run, this);
24 }
25 //-----------------------------------------------------------------------------
27 {
28  _stop = true;
29  if (_thread.joinable())
30  _thread.join();
31  _stop = false;
32  _ready = false;
33 }
34 //-----------------------------------------------------------------------------
35 //! if returns true, results are valid to be retrieved
37 {
38  return _ready;
39 }
40 //-----------------------------------------------------------------------------
42 {
43  return _stop;
44 }
45 //-----------------------------------------------------------------------------
46 // call set ready when custom run finished
48 {
49  _ready = true;
50 }
51 //-----------------------------------------------------------------------------
53 {
54  int n = 120;
55  int i = 0;
56  // do task
57  while (true)
58  {
59  using namespace std::chrono_literals;
60  std::this_thread::sleep_for(100ms);
61  Utils::log("AsyncWorker", "run til %d: %i", n, i);
62  if (stopRequested())
63  {
64  Utils::log("AsyncWorker", "stop requested");
65  break;
66  }
67  if (i == n)
68  break;
69 
70  i++;
71  }
72 
73  // task is ready
74  Utils::log("AsyncWorker", "run ready");
75  setReady();
76 }
77 //-----------------------------------------------------------------------------
Declaration of an async worker thread class.
bool isReady()
if returns true, results are valid to be retrieved
Definition: AsyncWorker.cpp:36
std::thread _thread
Definition: AsyncWorker.h:34
std::atomic_bool _ready
Definition: AsyncWorker.h:36
void setReady()
Definition: AsyncWorker.cpp:47
virtual void run()
Definition: AsyncWorker.cpp:52
std::atomic_bool _stop
Definition: AsyncWorker.h:35
void start()
Definition: AsyncWorker.cpp:20
bool stopRequested()
Definition: AsyncWorker.cpp:41
virtual ~AsyncWorker()
Definition: AsyncWorker.cpp:15
void log(const char *tag, const char *format,...)
logs a formatted string platform independently
Definition: Utils.cpp:1103