Check a task status inside HandleExt to handle concurrent issue
[platform/upstream/csr-framework.git] / src / framework / client / handle-ext.cpp
index 3a7b065..cf97924 100644 (file)
@@ -41,17 +41,32 @@ HandleExt::~HandleExt()
                this->m_worker.join();
 }
 
-void HandleExt::stop()
+void HandleExt::setStopFunc(std::function<void()> &&func)
+{
+       std::lock_guard<std::mutex> l(this->m_flagMutex);
+       this->m_stopFunc = std::move(func);
+}
+
+bool HandleExt::stop()
 {
        DEBUG("Stop & join worker...");
 
        {
                std::lock_guard<std::mutex> l(this->m_flagMutex);
+
+               if (!this->m_isRunning || this->m_stop)
+                       return false;
+
                this->m_stop = true;
+
+               if (this->m_stopFunc != nullptr)
+                       this->m_stopFunc();
        }
 
        if (this->m_worker.joinable())
                this->m_worker.join();
+
+       return true;
 }
 
 bool HandleExt::isStopped() const
@@ -79,11 +94,15 @@ void HandleExt::dispatchAsync(const std::shared_ptr<Task> &f)
        this->m_isRunning = true;
        this->m_stop = false;
 
-       // TODO: how to handle exceptions in workers
        this->m_worker = std::thread([this, f] {
                DEBUG("client async thread dispatched! tid: " << std::this_thread::get_id());
 
-               (*f)();
+               {
+                       // Wait for client lib API func returned & mutex freed by scoped-lock dtor
+                       // This is for invoking registered callbacks follows returning API func
+                       std::lock_guard<std::mutex> _l(this->m_dispatchMutex);
+               }
+                       (*f)();
 
                {
                        std::lock_guard<std::mutex> _l(this->m_flagMutex);