ACloudViewer  3.9.4
A Modern Library for 3D Data Processing
Task.cpp
Go to the documentation of this file.
1 // ----------------------------------------------------------------------------
2 // - CloudViewer: www.cloudViewer.org -
3 // ----------------------------------------------------------------------------
4 // Copyright (c) 2018-2024 www.cloudViewer.org
5 // SPDX-License-Identifier: MIT
6 // ----------------------------------------------------------------------------
7 
9 
10 #include <Logging.h>
11 
12 #include <atomic>
13 #include <thread>
14 
15 namespace cloudViewer {
16 namespace visualization {
17 namespace gui {
18 
19 namespace {
20 enum class ThreadState { NOT_STARTED, RUNNING, FINISHED };
21 }
22 
23 struct Task::Impl {
24  std::function<void()> func_;
25  std::thread thread_;
26  ThreadState state_;
27  std::atomic<bool> is_finished_running_;
28 };
29 
30 Task::Task(std::function<void()> f) : impl_(new Task::Impl) {
31  impl_->func_ = f;
32  impl_->state_ = ThreadState::NOT_STARTED;
33  impl_->is_finished_running_ = false;
34 }
35 
37  // TODO: if able to cancel, do so here
38  WaitToFinish();
39 }
40 
41 void Task::Run() {
42  if (impl_->state_ != ThreadState::NOT_STARTED) {
43  utility::LogWarning("Attempting to Run() already-started Task");
44  return;
45  }
46 
47  auto thread_main = [this]() {
48  impl_->func_();
49  impl_->is_finished_running_ = true;
50  };
51  impl_->thread_ = std::thread(thread_main); // starts thread
52  impl_->state_ = ThreadState::RUNNING;
53 }
54 
55 bool Task::IsFinished() const {
56  switch (impl_->state_) {
57  case ThreadState::NOT_STARTED:
58  return true;
59  case ThreadState::RUNNING:
60  return impl_->is_finished_running_;
61  case ThreadState::FINISHED:
62  return true;
63  }
64  utility::LogError("Unexpected thread state");
65 }
66 
68  if (impl_->state_ == ThreadState::RUNNING) {
69  impl_->thread_.join();
70  impl_->state_ = ThreadState::FINISHED;
71  }
72 }
73 
74 } // namespace gui
75 } // namespace visualization
76 } // namespace cloudViewer
Task(std::function< void()> f)
Definition: Task.cpp:30
~Task()
Will call WaitToFinish(), which may block.
Definition: Task.cpp:36
#define LogWarning(...)
Definition: Logging.h:72
#define LogError(...)
Definition: Logging.h:60
Generic file read and write utility for python interface.
std::atomic< bool > is_finished_running_
Definition: Task.cpp:27