TAMSVIZ
Visualization and annotation tool for ROS
loader.cpp
1 // TAMSVIZ
2 // (c) 2020 Philipp Ruppel
3 
4 #include "loader.h"
5 
6 void LoaderThread::start(const std::shared_ptr<void> &owner,
7  const std::function<void()> &fnc) {
8  std::unique_lock<std::mutex> lock(_mutex);
9  _queue.emplace_back(owner, fnc);
10  _condition.notify_one();
11 }
12 
13 void LoaderThread::cancel(const std::shared_ptr<void> &owner) {
14  std::unique_lock<std::mutex> lock(_mutex);
15  for (auto it = _queue.begin(); it != _queue.end();) {
16  if (it->first == owner) {
17  it = _queue.erase(it);
18  } else {
19  it++;
20  }
21  }
22 }
23 
24 LoaderThread::LoaderThread() {
25  _count = 0;
26  _thread = std::thread([this]() {
27  while (true) {
28  std::function<void()> job;
29  {
30  std::unique_lock<std::mutex> lock(_mutex);
31  while (true) {
32  if (_stop) {
33  return;
34  }
35  if (!_queue.empty()) {
36  _count = _queue.size();
37  job = _queue.front().second;
38  _queue.pop_front();
39  break;
40  }
41  _count = 0;
42  _condition.wait(lock);
43  }
44  }
45  started();
46  job();
47  finished();
48  }
49  });
50 }
51 
52 LoaderThread::~LoaderThread() {
53  {
54  std::unique_lock<std::mutex> lock(_mutex);
55  _stop = true;
56  _condition.notify_all();
57  }
58  _thread.join();
59 }
60 
61 const std::shared_ptr<LoaderThread> &LoaderThread::instance() {
62  static auto instance = std::make_shared<LoaderThread>();
63  return instance;
64 }