Scanframe Modular Application 0.1.0
Loading...
Searching...
No Matches
Thread.h
Go to the documentation of this file.
1#pragma once
4#include <misc/gen/Mutex.h>
5#include <misc/gen/TClosure.h>
6#include <misc/gen/TimeSpec.h>
7#include <misc/gen/target.h>
8#include <misc/global.h>
9#include <pthread.h>
10#include <string>
11#include <unistd.h>
12#include <utility>
13#if IS_WIN
14 #include <windows.h>
15#else
16 #include <sys/eventfd.h>
17#endif
18
19namespace sf
20{
21
28{
29 public:
33 typedef pthread_t handle_type;
34
38#if IS_WIN
39 typedef DWORD id_type;
40#else
41 typedef pid_t id_type;
42#endif
43
48 enum EStatus : int
49 {
53 tsInvalid = 0,
69 tsTerminated
70 };
71
76 {
77 public:
81 typedef ::pthread_attr_t* handle_type;
82
87
91 Attributes(const Attributes&) = delete;
92
96 Attributes& operator=(const Attributes&) = delete;
97
106
111
119
123 [[nodiscard]] size_t getStackSize() const;
124
131 void setStackSize(size_t sz);
132
137 {
139 spScheduleOther = SCHED_OTHER,
141 spScheduleFifo = SCHED_FIFO,
143 spScheduleRoundRobin = SCHED_RR,
144#if IS_WIN
145 spScheduleBatch = spScheduleOther,
146 spScheduleIdle = spScheduleOther,
147 spScheduleResetOnFork = spScheduleOther
148#else
149 spScheduleBatch = SCHED_BATCH,
150 spScheduleIdle = SCHED_IDLE,
151 spScheduleResetOnFork = SCHED_RESET_ON_FORK
152#endif
153 };
154
159
163 [[nodiscard]] ESchedulePolicy getSchedulePolicy() const;
164
168 inline operator handle_type() const;
169
170 private:
174 handle_type _attributes;
175 };
176
182
189
196 virtual void terminate();
197
204
209
215 [[nodiscard]] EStatus getStatus() const;
216
223 [[nodiscard]] const char* getStatusText(EStatus status = (EStatus) -1) const;
224
228 [[nodiscard]] int getExitCode() const;
229
233 [[nodiscard]] bool isSelf() const;
234
238 [[nodiscard]] id_type getId() const;
239
243 [[nodiscard]] handle_type getHandle() const;
244
249
253 inline operator handle_type() const;
254
258 enum EPriority : int
259 {
260 tpIdle = -15,
261 tpLowest = -2,
262 tpBelowNormal = -1,
263 tpNormal = 0,
264 tpAboveNormal = 1,
265 tpHighest = 2,
266 tpTimeCritical = 15
267 };
268
274 void setName(const char* name);
275
280 std::string getName() const;
281
285 [[nodiscard]] int getPriority() const;
286
292 bool setPriority(int pri, int sp = Attributes::spScheduleOther);
293
299
304 [[nodiscard]] bool shouldTerminate() const;
305
312 void exit(int code);
313
318 inline void setDebug(bool yn);
319
325 static bool yieldToOther();
326
331 class ThreadException : public ExceptionBase<ThreadException>
332 {
333 public:
337 explicit ThreadException(const char* message) noexcept
338 : ExceptionBase()
339 {
340 formatMessage(message);
341 }
342
346 template<typename... Args>
347 explicit ThreadException(const char* format, Args&&... args) noexcept
348 : ExceptionBase()
349 {
350 formatMessage(format, args...);
351 }
352 };
353
359 {
360 public:
361 explicit TerminateException(const std::string& from)
362 : ThreadException("Terminating from %s", from.c_str())
363 {}
364 };
365
370 bool sleep(const TimeSpec& ts, bool alertable = true) const;
371
378
384
390
396
402 static size_t getCurrentStackSize();
403
407 Thread(const Thread&) = delete;
408
412 const Thread& operator=(const Thread&) = delete;
413
417 [[nodiscard]] inline bool isDebug() const;
418
419 protected:
423 Thread(const std::string& name);
424
429 Thread(bool);
430
434 virtual ~Thread();
435
441 virtual void cleanup();
442
443 protected:
448 virtual int run() = 0;
449
454
455 private:
459 int create();
460
464 void setConditionWaiting(Condition* condition);
465
469 std::string _name;
473 Mutex _mutex{"thread"};
477 pid_t _threadId{0};
481 handle_type _handle{0};
485 EStatus _status{EStatus::tsInvalid};
489 bool _terminationRequested{false};
493 TimeSpec _terminationTime{};
497 TimeSpec _startupTime{0.3};
503 Condition* _condition{nullptr};
510 Condition* _condition_waiting{nullptr};
514 bool _isMain{false};
518 union
519 {
520 void* Ptr;
521 intptr_t Code;
522 } _exitCode{nullptr};
523
527 bool _debug{false};
528
533 friend class Condition;
534};
535
536inline Thread::operator handle_type() const
537{
538 return _handle;
539}
540
541inline Thread::Attributes::operator handle_type() const
542{
543 return _attributes;
544}
545
546inline void Thread::setDebug(bool yn)
547{
548 _debug = yn;
549}
550
551inline bool Thread::isDebug() const
552{
553 return _debug;
554}
555
560{
561 public:
565 ThreadMain();
569 int run() override;
570};
571
573 : Thread(true)
574{}
575
576inline int ThreadMain::run()
577{
578 return 0;
579}
580
581}// namespace sf
Wrapper for the pthread_cond mechanism.
Definition Condition.h:16
Exception implementation inherited from std::exception.
Definition Exception.h:18
Lightweight intra process thread synchronization.
Definition Mutex.h:17
Wrapper class for the main thread.
Definition Thread.h:560
int run() override
Overrides run function but does nothing since it is the main thread.
Definition Thread.h:576
ThreadMain()
Calls on protected boolean constructor.
Definition Thread.h:572
Thread attributes used internally for starting a thread.
Definition Thread.h:76
Attributes(Thread::handle_type th)
Initialize using the passed thread handle.
~Attributes()
Destructor.
::pthread_attr_t * handle_type
Definition Thread.h:81
Attributes & operator=(const Attributes &)=delete
Prevent assignment.
ESchedulePolicy
Thread schedule policies.
Definition Thread.h:137
Attributes(const Attributes &)=delete
Prevent copying.
void setup(Thread::handle_type th=0)
When the handle is '0' the current thread is used.
Attributes()
Default Constructor.
size_t getStackSize() const
Gets the stack size of the thread which initialized it.
ESchedulePolicy getSchedulePolicy() const
Gets the current set scheduling priority.
void setStackSize(size_t sz)
Sets the stack size for a new thread.
void setSchedulePolicy(ESchedulePolicy policy)
Sets scheduling priority for the to be started thread.
Special thread exception thrown by system blocking functions to terminate the thread.
Definition Thread.h:359
TerminateException(const std::string &from)
Definition Thread.h:361
Thread exception.
Definition Thread.h:332
ThreadException(const char *format, Args &&... args) noexcept
Formatting constructor.
Definition Thread.h:347
ThreadException(const char *message) noexcept
Constructor initializing message.
Definition Thread.h:337
Thread wrapper class to be used for attachment to an existing thread or a new to be created thread....
Definition Thread.h:28
void waitForExit()
Waits for the thread to exit.
EStatus
Thread states enumeration.
Definition Thread.h:49
@ tsRunning
Thread is running.
Definition Thread.h:61
@ tsCreated
The thread is created but not started.
Definition Thread.h:57
@ tsFinished
The thread has run and finished.
Definition Thread.h:65
bool isDebug() const
Gets the debug flag.
Definition Thread.h:551
intptr_t Code
Definition Thread.h:521
bool shouldTerminate() const
Call by the thread itself to determine if it should terminate. Another thread then this one it too bu...
const char * getStatusText(EStatus status=(EStatus) -1) const
Returns the status a string.
Thread(const Thread &)=delete
Copying constructor disabled and not implemented.
static int getTerminationSignal()
Returns the thread termination signal.
handle_type getHandle() const
Returns the handle of this instance.
bool sleep(const TimeSpec &ts, bool alertable=true) const
Makes the current thread sleep for the given amount time until a signal interrupts when alertable is ...
bool isSelf() const
Returns true if the calling thread is this thread.
pthread_t handle_type
Local declaration of the handle type.
Definition Thread.h:33
static id_type getCurrentId()
Gets the current thread ID.
Thread(const std::string &name)
Protected constructor which demands to derive a class.
virtual void cleanup()
Function which can be overloaded in a derived class.
virtual ~Thread()
Virtual Destructor.
static id_type getMainId()
Gets the main thread ID.
int getPriority() const
Gets the current priority of this instance.
std::string getName() const
Gets the name of the thread available in the debugger.
bool setPriority(int pri, int sp=Attributes::spScheduleOther)
Can pass an enumerate EPriority for simplicity.
EStatus getStatus() const
Returns the status.
virtual int run()=0
Function which needs to be overloaded in a derived class. This function is the actual thread function...
void * Ptr
Definition Thread.h:520
void setTerminationTime(const TimeSpec &ts)
Sets the time needed for the thread to terminate. Default is one 100 ms.
static size_t getCurrentStackSize()
Returns the current thread initial stack size.
void setName(const char *name)
Sets the name of the thread available in the debugger. The name is clipped to the first 15 characters...
Thread(bool)
Wraps this class around the main thread of the application. The boolean bogus argument is to be diffe...
static bool yieldToOther()
Yield control of the current thread. The name 'Yield()' is defined as a macro in MingW.
static Thread & getCurrent()
Gets the sf::Thread instance reference of the current thread.
void TerminationSignal()
Called to unblock system functions.
void terminateAndWait()
Same as calling Terminate() and thereafter calling WaitForExit()
EPriority
Enumeration of thread priorities.
Definition Thread.h:259
int getExitCode() const
Returns the exist value of the thread function.
const Thread & operator=(const Thread &)=delete
Copy constructor not implemented.
void exit(int code)
Alternative to returning from then run() method. Called from within the thread that wants to exit ear...
void setDebug(bool yn)
Enables debug logging.
Definition Thread.h:546
virtual void terminate()
Can be overloaded to signal the thread to terminate.
handle_type start(const Attributes &attr)
Starts a thread which calls on its turn the overridden function Run().
id_type getId() const
Returns the thread ID. Is currently in Linux the same as the handle.
pid_t id_type
Local declaration of the thread id type.
Definition Thread.h:41
static handle_type getCurrentHandle()
Return the current thread handle.
handle_type start()
Starts a thread with default attributes which calls on its turn the overridden run().
friend void installSignalHandlers()
#define _MISC_CLASS
Definition misc/global.h:40
Definition Application.h:10
_MISC_FUNC bool isDebug()
Gets the debug status.
Class wrapper for timespec structure to modify.
Definition TimeSpec.h:12