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::stop()
46 DEBUG("Stop & join worker...");
49 std::lock_guard<std::mutex> l(this->m_flagMutex);
53 if (this->m_worker.joinable())
54 this->m_worker.join();
57 bool HandleExt::isStopped() const
59 std::lock_guard<std::mutex> l(this->m_flagMutex);
63 bool HandleExt::isRunning() const
65 std::lock_guard<std::mutex> l(this->m_flagMutex);
66 return this->m_isRunning;
69 void HandleExt::dispatchAsync(const std::shared_ptr<Task> &f)
71 std::lock_guard<std::mutex> l(this->m_flagMutex);
73 if (this->m_isRunning)
74 ThrowExc(BusyError, "Worker is already running. Async is busy!");
76 if (this->m_worker.joinable())
77 this->m_worker.join();
79 this->m_isRunning = true;
82 // TODO: how to handle exceptions in workers
83 this->m_worker = std::thread([this, f] {
84 DEBUG("client async thread dispatched! tid: " << std::this_thread::get_id());
89 std::lock_guard<std::mutex> _l(this->m_flagMutex);
90 this->m_isRunning = false;
93 DEBUG("client async thread done! tid: " << std::this_thread::get_id());
97 void HandleExt::add(ResultPtr &&ptr)
99 std::lock_guard<std::mutex> l(this->m_resultsMutex);
101 this->m_results.emplace_back(std::move(ptr));
104 void HandleExt::add(ResultListPtr &&ptr)
106 std::lock_guard<std::mutex> l(this->m_resultsMutex);
108 this->m_resultLists.emplace_back(std::move(ptr));
111 } // namespace Client