Keyple Util C++ Library 2.0.0
Reference Terminal Reader API for C++
Thread.h
Go to the documentation of this file.
1/**************************************************************************************************
2 * Copyright (c) 2021 Calypso Networks Association https://calypsonet.org/ *
3 * *
4 * See the NOTICE file(s) distributed with this work for additional information regarding *
5 * copyright ownership. *
6 * *
7 * This program and the accompanying materials are made available under the terms of the Eclipse *
8 * Public License 2.0 which is available at http://www.eclipse.org/legal/epl-2.0 *
9 * *
10 * SPDX-License-Identifier: EPL-2.0 *
11 **************************************************************************************************/
12
13#pragma once
14
15#include <chrono>
16#include <future>
17#include <thread>
18
19namespace keyple {
20namespace core {
21namespace util {
22namespace cpp {
23
24class Thread {
25public:
30
39 Thread(const std::string& name)
40 : mDone(false), mAlive(false), mName(name), mInterrupted(false), mDedicatedThread(false) {}
41
49 Thread() : Thread("Thread-x") {}
50
54 virtual ~Thread() = default;
55
59 void setName(const std::string& name)
60 {
61 mName = name;
62 }
63
75 void start()
76 {
77 mAlive = true;
78 mDedicatedThread = true;
79
80 mThread = std::async(std::launch::async, &runThread, this);
81 }
82
86 void run()
87 {
88 mAlive = true;
89
90 this->execute();
91
92 mAlive = false;
93 mDone = true;
94 }
95
102 int join()
103 {
104 int result = -1;
105
106 if (isAlive() == true) {
107 mThread.wait();
108 }
109
110 return result;
111 }
112
116 bool isAlive()
117 {
118 /* Perform live check if dedicated thread is in use */
119 if (mDedicatedThread == true) {
120 mAlive = (mThread.wait_for(std::chrono::milliseconds(0)) != std::future_status::ready);
121 }
122
123 return mAlive;
124 }
125
138 static void sleep(long millis)
139 {
140 std::this_thread::sleep_for(std::chrono::milliseconds(millis));
141 }
142
169 {
170 mInterrupted = true;
171 }
172
176 bool isInterrupted() const
177 {
178 return mInterrupted;
179 }
180
184 std::string getName()
185 {
186 return mName;
187 }
188
192 void setUncaughtExceptionHandler(std::shared_ptr<UncaughtExceptionHandler> eh)
193 {
194 mUncaughtExceptionHandler = eh;
195 }
196
197protected:
201 bool mDone;
202
203private:
207 bool mAlive;
208
212 std::string mName;
213
217 bool mInterrupted;
218
222 std::future<void> mThread;
223
227 std::shared_ptr<UncaughtExceptionHandler> mUncaughtExceptionHandler;
228
232 bool mDedicatedThread;
233
241 static void runThread(void* arg)
242 {
243 ((Thread*)arg)->execute();
244 }
245
249 virtual void execute() = 0;
250};
251
252}
253}
254}
255}
Thread(const std::string &name)
Definition: Thread.h:39
void setUncaughtExceptionHandler(std::shared_ptr< UncaughtExceptionHandler > eh)
Definition: Thread.h:192
void setName(const std::string &name)
Definition: Thread.h:59
static void sleep(long millis)
Definition: Thread.h:138