diff options
author | dec05eba <dec05eba@protonmail.com> | 2021-07-21 14:46:48 +0200 |
---|---|---|
committer | dec05eba <dec05eba@protonmail.com> | 2021-07-21 14:46:48 +0200 |
commit | a76dabb12734154177a78033324b40365e7c6f21 (patch) | |
tree | dab1d6b997ba283dfcc7f9dd12adee96dd631dc2 /include | |
parent | 3c16cb376669e4ae500d22529b40112c761088c0 (diff) |
Fix freeze on search reset in manga combined plugin. Fix multithreading issues in AsyncTask
Diffstat (limited to 'include')
-rw-r--r-- | include/AsyncTask.hpp | 31 |
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 |