2 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
17 * @file handle-ext.cpp
18 * @author Kyungwook Tak (k.tak@samsung.com)
20 * @brief handle with async request extension
22 #include "client/handle-ext.h"
26 #include "common/audit/logger.h"
27 #include "common/exception.h"
32 HandleExt::HandleExt(SockId id, ContextShPtr &&context) :
33 Handle(id, std::move(context)), m_stop(false), m_isRunning(false)
37 HandleExt::~HandleExt()
39 DEBUG("Destroying extended handle... join worker...");
40 if (this->m_worker.joinable())
41 this->m_worker.join();
44 void HandleExt::setStopFunc(std::function<void()> &&func)
46 std::lock_guard<std::mutex> l(this->m_flagMutex);
47 this->m_stopFunc = std::move(func);
50 void HandleExt::stop()
52 DEBUG("Stop & join worker...");
55 std::lock_guard<std::mutex> l(this->m_flagMutex);
58 if (this->m_stopFunc != nullptr)
62 if (this->m_worker.joinable())
63 this->m_worker.join();
66 bool HandleExt::isStopped() const
68 std::lock_guard<std::mutex> l(this->m_flagMutex);
72 bool HandleExt::isRunning() const
74 std::lock_guard<std::mutex> l(this->m_flagMutex);
75 return this->m_isRunning;
78 void HandleExt::dispatchAsync(const std::shared_ptr<Task> &f)
80 std::lock_guard<std::mutex> l(this->m_flagMutex);
82 if (this->m_isRunning)
83 ThrowExc(CSR_ERROR_BUSY, "Worker is already running. Async is busy!");
85 if (this->m_worker.joinable())
86 this->m_worker.join();
88 this->m_isRunning = true;
91 this->m_worker = std::thread([this, f] {
92 DEBUG("client async thread dispatched! tid: " << std::this_thread::get_id());
95 // Wait for client lib API func returned & mutex freed by scoped-lock dtor
96 // This is for invoking registered callbacks follows returning API func
97 std::lock_guard<std::mutex> _l(this->m_dispatchMutex);
102 std::lock_guard<std::mutex> _l(this->m_flagMutex);
103 this->m_isRunning = false;
106 DEBUG("client async thread done! tid: " << std::this_thread::get_id());
110 void HandleExt::add(ResultPtr &&ptr)
112 std::lock_guard<std::mutex> l(this->m_resultsMutex);
114 this->m_results.emplace_back(std::move(ptr));
117 void HandleExt::add(ResultListPtr &&ptr)
119 std::lock_guard<std::mutex> l(this->m_resultsMutex);
121 this->m_resultLists.emplace_back(std::move(ptr));
124 } // namespace Client