2 * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
4 * Contact: Bumjin Im <bj.im@samsung.com>
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License
19 * @file service-thread.h
20 * @author Bartlomiej Grzelewski (b.grzelewski@samsung.com)
21 * @author Zofia Abramowska (z.abramowska@samsung.com)
23 * @brief Implementation of threads.
26 #ifndef _CENT_KEY_SERVICE_THREAD_
27 #define _CENT_KEY_SERVICE_THREAD_
35 #include <condition_variable>
37 #include <crypto-init.h>
41 #include <dpl/exception.h>
43 #include "generic-event.h"
49 typedef std::function<void(void)> EventDescription;
56 : m_state(State::NoThread)
61 assert(m_state == State::NoThread);
62 m_thread = std::thread(ThreadLoopStatic, this);
63 m_state = State::Work;
67 assert(m_state != State::NoThread);
69 std::lock_guard<std::mutex> lock(m_eventQueueMutex);
71 m_waitCondition.notify_one();
74 m_state = State::NoThread;
77 virtual ~ServiceThread()
79 assert((m_state == State::NoThread) && "Thread was not stopped before ServiceThread destruction!");
84 * This function is always called from ThreadService::ThreadEvent where fun
85 * is created as a temporary object and therefore will not be copied.
87 void CreateEvent(std::function<void(void)> fun)
89 EventDescription description;
90 description = std::move(fun);
92 std::lock_guard<std::mutex> lock(m_eventQueueMutex);
93 m_eventQueue.push(description);
95 m_waitCondition.notify_one();
98 static void ThreadLoopStatic(ServiceThread *ptr) {
101 // cleanup openssl in every thread
102 deinitOpenSslThread();
107 EventDescription description;
109 std::unique_lock<std::mutex> ulock(m_eventQueueMutex);
112 if (!m_eventQueue.empty()) {
113 description = m_eventQueue.front();
116 m_waitCondition.wait(ulock);
121 UNHANDLED_EXCEPTION_HANDLER_BEGIN
125 UNHANDLED_EXCEPTION_HANDLER_END
130 std::thread m_thread;
131 std::mutex m_eventQueueMutex;
132 std::queue<EventDescription> m_eventQueue;
133 std::condition_variable m_waitCondition;
141 #endif // _CENT_KEY_SERVICE_THREAD_