aboutsummaryrefslogtreecommitdiff
path: root/include
diff options
context:
space:
mode:
Diffstat (limited to 'include')
-rw-r--r--include/AsyncTask.hpp31
1 files changed, 27 insertions, 4 deletions
diff --git a/include/AsyncTask.hpp b/include/AsyncTask.hpp
index 6148923..45b3397 100644
--- a/include/AsyncTask.hpp
+++ b/include/AsyncTask.hpp
@@ -3,6 +3,7 @@
#include "Program.hpp"
#include <thread>
#include <future>
+#include <mutex>
namespace QuickMedia {
template <class T, class... Args>
@@ -13,6 +14,7 @@ namespace QuickMedia {
AsyncTask() = default;
AsyncTask(CallbackFunc callback_func, Args&&... args) {
+ std::lock_guard<std::mutex> lock(mutex);
std::promise<T> promise;
future = promise.get_future();
thread = std::thread(&AsyncTask::thread_handler, this, std::move(promise), std::move(callback_func), std::forward<Args>(args)...);
@@ -20,12 +22,14 @@ namespace QuickMedia {
AsyncTask(AsyncTask &&other) {
cancel();
+ std::lock_guard<std::mutex> lock(mutex);
thread = std::move(other.thread);
future = std::move(other.future);
}
AsyncTask& operator=(AsyncTask &&other) {
cancel();
+ std::lock_guard<std::mutex> lock(mutex);
thread = std::move(other.thread);
future = std::move(other.future);
return *this;
@@ -36,22 +40,40 @@ namespace QuickMedia {
}
bool valid() {
+ std::lock_guard<std::mutex> lock(mutex);
return future.valid();
}
bool ready() {
+ std::lock_guard<std::mutex> lock(mutex);
return future.valid() && future.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
}
T get() {
- thread.join();
- return future.get();
+ std::lock_guard<std::mutex> lock(mutex);
+ if constexpr(std::is_same<T, void>::value) {
+ if(thread.joinable()) {
+ thread.join();
+ future.get();
+ }
+ } else {
+ T result;
+ if(thread.joinable()) {
+ thread.join();
+ result = std::move(future.get());
+ }
+ return result;
+ }
}
void cancel() {
- if(valid()) {
+ std::lock_guard<std::mutex> lock(mutex);
+ if(future.valid()) {
program_kill_in_thread(thread.get_id());
- get();
+ if(thread.joinable()) {
+ thread.join();
+ future.get();
+ }
}
}
private:
@@ -66,5 +88,6 @@ namespace QuickMedia {
private:
std::thread thread;
std::future<T> future;
+ std::mutex mutex;
};
} \ No newline at end of file