44 *
55 */
66
7+ #include < atomic>
8+ #include < exception>
9+ #include " Common/Cpp/Containers/Pimpl.tpp"
710#include " SpinPause.h"
11+ #include " Mutex.h"
12+ #include " ConditionVariable.h"
813#include " AsyncTask.h"
14+ #include " AsyncTaskCore.h"
915
1016// #include <iostream>
1117// using std::cout;
@@ -15,54 +21,55 @@ namespace PokemonAutomation{
1521
1622
1723
24+
25+ AsyncTask::AsyncTask (AsyncTask&&) = default ;
26+ AsyncTask& AsyncTask::operator =(AsyncTask&&) = default ;
27+
28+
29+ AsyncTask::AsyncTask ()
30+ : m_sanitizer(" AsyncTask" )
31+ {}
32+ AsyncTask::AsyncTask (std::function<void ()> task)
33+ : m_core(CONSTRUCT_TOKEN, std::move(task))
34+ , m_sanitizer(" AsyncTask" )
35+ {}
36+
1837AsyncTask::~AsyncTask (){
19- State state = m_state.load (std::memory_order_acquire);
20- if (state == State::NOT_STARTED || state == State::SAFE_TO_DESTRUCT){
21- // cout << "Already Done: " << (int)state << endl;
22- return ;
23- }
24-
25- {
26- std::unique_lock<Mutex> lg (m_lock);
27- m_cv.wait (lg, [this ]{
28- return m_state.load (std::memory_order_relaxed) != State::RUNNING;
29- });
30- }
31-
32- while (m_state.load (std::memory_order_acquire) != State::SAFE_TO_DESTRUCT){
33- pause ();
34- }
35-
36- // cout << "Late Finish" << endl;
38+ wait_and_ignore_exceptions ();
3739}
3840
3941
40- void AsyncTask::report_cancelled () noexcept {
41- {
42+ bool AsyncTask::is_finished () const noexcept {
4243#ifdef PA_SANITIZE_AsyncTask
43- auto scope = m_sanitizer.check_scope ();
44+ auto scope = m_sanitizer.check_scope ();
4445#endif
45- m_state.store (State::FINISHED, std::memory_order_release);
46- {
47- std::lock_guard<Mutex> lg (m_lock);
48- }
49- m_cv.notify_all ();
50- }
51- m_state.store (State::SAFE_TO_DESTRUCT, std::memory_order_release);
46+ return m_core->is_finished ();
5247}
53- void AsyncTask::run () noexcept {
54- {
48+
49+ void AsyncTask::wait_and_ignore_exceptions () noexcept {
50+ m_core.clear ();
51+ }
52+ void AsyncTask::wait_and_rethrow_exceptions (){
5553#ifdef PA_SANITIZE_AsyncTask
56- auto scope = m_sanitizer.check_scope ();
54+ auto scope = m_sanitizer.check_scope ();
5755#endif
58- try {
59- m_task ();
60- }catch (...){
61- std::lock_guard<Mutex> lg (m_lock);
62- m_exception = std::current_exception ();
63- }
64- }
65- report_cancelled ();
56+ m_core->wait_and_rethrow_exceptions ();
57+ }
58+
59+
60+ void AsyncTask::report_started (){
61+ #ifdef PA_SANITIZE_AsyncTask
62+ auto scope = m_sanitizer.check_scope ();
63+ #endif
64+ m_core->report_started ();
65+ }
66+ void AsyncTask::report_cancelled () noexcept {
67+ m_sanitizer.check_usage ();
68+ m_core->report_cancelled ();
69+ }
70+ void AsyncTask::run () noexcept {
71+ m_sanitizer.check_usage ();
72+ m_core->run ();
6673}
6774
6875
0 commit comments