Libftpp
A modern C++ library
persistent_worker.cpp
Go to the documentation of this file.
1 #include "persistent_worker.hpp"
2 
4 {
5  _thread = std::thread(&PersistentWorker::loop, this);
6 }
7 
9 {
10  {
11  std::lock_guard<std::mutex> lock(_mtx);
12  _running = false;
13  }
14  _cv.notify_one();
15  if (_thread.joinable())
16  _thread.join();
17 }
18 
19 void PersistentWorker::addTask(const std::string& name, const std::function<void()>& jobToExecute)
20 {
21  std::lock_guard<std::mutex> lock(_mtx);
22  _tasks[name] = jobToExecute;
23  _cv.notify_one();
24 }
25 
26 void PersistentWorker::removeTask(const std::string& name)
27 {
28  std::lock_guard<std::mutex> lock(_mtx);
29  _tasks.erase(name);
30 }
31 
32 #include <iostream>
33 void PersistentWorker::loop()
34 {
35  std::unordered_map<std::string, std::function<void()>> copy;
36 
37  bool keepGoing = true;
38  while (keepGoing)
39  {
40  std::unique_lock<std::mutex> lock(_mtx);
41  _cv.wait(lock, [this] { return !_running || !_tasks.empty(); });
42 
43  if (!_running)
44  return;
45 
46  copy = _tasks;
47  lock.unlock();
48 
49  for (std::pair<std::string, std::function<void()>> element : copy)
50  {
51  try
52  {
53  element.second();
54  }
55  catch (const std::exception& e)
56  {
57  // Log explicite et non bloquant
58  std::cerr << "[PersistentWorker] Task '" << element.first
59  << "' threw an exception: " << e.what() << std::endl;
60  }
61  catch (...)
62  {
63  // Pour attraper les exceptions non-std
64  std::cerr << "[PersistentWorker] Task '" << element.first
65  << "' threw an unknown exception." << std::endl;
66  }
67  std::this_thread::sleep_for(std::chrono::milliseconds(PAUSE_BT_TASK));
68  }
69 
70  {
71  std::lock_guard<std::mutex> lock(_mtx);
72  keepGoing = _running;
73  }
74  }
75 }
void removeTask(const std::string &name)
void addTask(const std::string &name, const std::function< void()> &jobToExecute)
#define PAUSE_BT_TASK