12 /*======================================================================*//**
14 This @ref rthread thread library provides an easier and sufficiently-complete
15 object-oriented thread interface class for C++ that adds a properly-honoured
16 destructor, and without terminating the entire application when the thread
17 throws an exception. This class also provides a virtual method for
18 optionally handling all exceptions (that are otherwise ignored by default) in
19 a penultimate stage prior to commencing onward to the final destructor stage.
21 POSIX threads are the foundation of the rthread class, and the resulting C++
22 interface will probably seem familiar to those who are familliar with Java.
25 This is meant to be a safe and easy-to-use thread class for C++, which is
26 intended to make thread sub-classing straight-forward in a logical manner for
27 developers. Some of the key features are:
29 - Customizable constructor that doesn't automatically start the thread
30 - Better control with the @ref start() method to start a previously
32 - Abstract @ref run() method (required)
33 - This method contains the code that will be run in its own thread
34 - Customizable destructor that occurs only after the thread ends (which
35 is particularly useful for daemon threads {a.k.a., detached threads})
36 - Customizable exception handler method (just subclass it to use it)
37 - Most methods are designed to be thread-safe (e.g., status methods)
39 Some advanced features are planned that exceed what the basic thread
40 functions provide, but are also needed:
42 - thread groups (separate class), possibly with support for including
43 threads in multiple groups
44 - thread pool (separate class)
47 I created this class to make it easier to write internet server daemons. I
48 started out using C-style thread functions (because C++ doesn't come with a
49 thread class that can be sub-classed), and even with std::jthreads I ran into
50 a serious problem with the thread's destructor executing while the thread was
51 still running (the code that started it went out of scope) -- this is not
52 what I expected because the running thread should really be an additional
53 criteria for thread destruction (this is a serious concern since the
54 premature destruction of a running thread usually results in a segmentation
55 fault or other unpredictable behaviour that has the potential to cause the
56 Operating System to exhibit other strange behaviours or even crash entirely).
58 After looking for existing solutions (none of which resolved the ineherent
59 problems with threads in C++), I embarked on creating this rthread class,
60 which was highly educational but also wasn't difficult. The end result is a
61 small class that's easy to maintain, eliminates the reliability concerns, and
62 is easy to use primarily because C++ thoroughly supports subclassing.
64 My background in programming began when I was a young child, teaching myself
65 BASIC and then machine language (when I found BASIC to be too limited) before
66 moving on to other languages like Perl and Java many years later. Eventually
67 I circled around to C (which I chose to learn the hard way by writing some
68 PostgreSQL extensions) and then C++ a few years after that. I have a lot of
69 experience with programming threadded applications on a variety of platforms
70 that support pthreads (including Novell's NetWare), running application code
71 I created that ran hundreds of thousands of threads successfully serving a
72 similar number of users globally without slowdowns or crashes.
74 - 2022-Oct-22 v1.00 Initial version
75 - 2024-Oct-23 v1.00 Various minor improvements to the documentation since
78 @author Randolf Richardson
80 *///=========================================================================
83 pthread_t __rthread_pthread_id = 0;
84 std::atomic_bool __rthread_running = false;
85 std::atomic_bool __rthread_detached = false;
86 std::atomic_bool __rthread_death = false; // Destructor changes this to TRUE
87 std::atomic_bool __rthread_reuseable = false; // Change this to a total-run-count // If set to TRUE, then this thread can be run again without needing to be re-constructed
88 std::atomic_ulong __rthread_used = 0; // Total number of times this thread was started
90 /*======================================================================*//**
91 Return Code check, and throws an rthread-specific exception if an error
92 occurred, which is indicated by @c -1 (a lot of example code shows @c < @c 1
93 comparisons, but we specifically test for @c -1 because the documentation
94 clearly states @c -1. This is important because a system that can support an
95 extremely high number of socket handles might, in theory, assign handles with
96 values that get interpreted as negative integers, and so less-than-zero tests
97 would result in dropped packets or dropped sockets (any such socket code that
98 allocates such handles obviously must not ever allocate @c -1 since this
99 would definitely be misinterpreted as an error).
101 If rc is not @c -1, then it is simply returned as is.
103 If n is nonzero and rc is 0, then n will override errno. (This option is
104 provided to accomodate the few socket library functions that return values
105 that are never errors, and expect the developer to rely on other means of
106 detecting whether an error occurred. This is an example of where Object
107 Oriented Programming is helpful in making things better.)
108 @returns Original value of @c rc (if no exceptions were thrown)
109 *///=========================================================================
110 const int __rc_check_pthread(
113 /// Exception handling flags (see @ref rex::REX_FLAGS for details)
114 const int flags = rex::rex::REX_FLAGS::REX_DEFAULT) {
116 randolf::rex::mk_exception("", rc, flags); // This function doesn't return (this code ends here)
119 }; // -x- int __rc_check_pthread -x-
122 /*======================================================================*//**
125 You can subclass this constructor and/or create parameterized constructors,
126 any of which may throw exceptions (even though this default one doesn't).
128 This is particularly useful for performing pre-run setup before starting the
129 thread (see the @ref run() and @ref start() methods for details), especially
130 with threads that start running in response to external events (such as user
131 interaction events, incoming internet socket connections, etc.).
132 *///=========================================================================
133 rthread() noexcept {}; // -x- constructor rthread -x-
135 /*======================================================================*//**
137 Default destructor. Called only after two conditions are met:
138 1. this rthread has gone out of scope
139 2. termination of the underlying pthread (this is different from the
140 standard C++ implementation of threads and jthreads, which don't have
143 Exceptions are handled by the @ref _rthread_exceptions() method before this
144 destructor is activated.
146 You can add your own destructor to safely ensure that files and sockets are
147 closed, and that resources are freed, deallocated, deleted, etc., which is
148 essential to preventing various types of resource leaks if your thread code
149 (in the @ref run() method) exited early due to an unexpected exception (it is
150 the developer's responsibility to ensure resources are managed properly, and
151 this destructor provides a means of handling this reliably).
153 Logging, re-queuing, semaphore completions, etc., can also be handled in this
154 method because it runs after the termination of the underlying pthread.
156 Do not throw exceptions from this method. If you're relying on a function or
157 a class that might throw exceptions (intended or otherwise), then you need to
158 take care to at least utilize a final try/catch block for @c std::exception.
159 *///=========================================================================
160 virtual ~rthread() noexcept { // Destructor (subclass destructor will run first if it's defined)
161 __rthread_death = true;
162 if (__rthread_running && !__rthread_detached) {
163 pthread_detach(__rthread_pthread_id);
164 __rthread_detached = true;
165 } // -x- if __rthread_running -x-
166//std::cout << "rthread " << __rthread_pthread_id << " destruction completed / __rthread_running=" << __rthread_running << std::endl;
167 if (__rthread_running) pthread_cancel(__rthread_pthread_id); // This must be the very last; any commands after this will cause: terminate called without an active exception
168 // TODO: pthread_setcancelstate, pthread_setcanceltype, and pthread_testcancel
169 }; // -x- destructor rthread -x-
171 /*======================================================================*//**
173 Final rthread exception handler.
174 If an uncaught exception is thrown from the @ref run() method in a running
175 rthread, then it will be handled by this method (which is still technically
176 running on the underlying pthread). Override this method to handle known and
177 unknown exceptions gracefully, before the destructor (or reinitiator) runs.
179 If @c e is @c nullptr it means an unknown exception was thrown (e.g.,
180 internally we literally caught `(...)` (other exception), in which case
181 you'll need to use @c std::current_exception() to access it.
183 For a reuseable rthread, the @ref running status will be set to false during
184 @ref _rthread_reinitialize execution, which can be useful for handling those
185 exceptions separately within this code (by testing for the @ref running()
187 *///=========================================================================
188 virtual void _rthread_exceptions(
189 /// Exceptions (see warning, immediately above)
190 std::exception* e) noexcept {}; // -x- void rthread_exceptions -x-
192 /*======================================================================*//**
194 Re-initialize internal variables, refresh resources, etc., before re-running
195 a @ref reuseable rthread.
196 When utilizing the reuseable feature, this method can be thought of as having
197 similar functionality to that of the constructor, except that it is used to
198 do the following to bring internal variables and resources back to the same
199 state that the constructor originally initialized them to, and thus reducing
200 construction overhead (some variables may not need re-initializing, which can
201 also help to further-reduce overhead):
202 - close any open files, sockets, etc., that need to be closed (or reset
203 file pointers instead of re-opening files)
204 - reset/clear variables and memory structures to their expected defaults
205 (or free-and-allocate resources that can't be reset or cleared reliably)
206 - re-add @c this to a thread pool or concurrent queue of ready rthreads
209 If there is any clean-up, logging, etc., peformed in the destructor that also
210 needs to be performed here, the best approach is to create a private method
211 for those particular actions and then call it from this method as well as the
212 destructor for better operational consistency.
214 *///=========================================================================
215 virtual void _rthread_reinitialize() noexcept {}; // -x- void rthread_reinitialize -x-
217 /*======================================================================*//**
219 Daemonize this rthread.
221 If this rthread was previously detached, then this method has no effect (but
222 won't cause the randolf::rex::xEINVAL exception to be thrown; there may be
223 other reasons for this exception to be thrown).
225 This method is thread-safe.
227 @throws randolf::rex::xEINVAL Not a joinable rthread
228 @throws randolf::rex::xESRCH A pthread with the underlying @c pthread_id
229 couldn't be found (underlying pthread doesn't exist)
231 @returns The same rthread object so as to facilitate stacking
234 *///=========================================================================
236 if (__rthread_running && !__rthread_detached) {
237 __rc_check_pthread(pthread_detach(__rthread_pthread_id));
238 __rthread_detached = true;
239 } // -x- if __rthread_running -x-
241 }; // -x- rthread* detach -x-
243 /*======================================================================*//**
245 Find out whether this rthread is daemonized.
247 This method is thread-safe.
248 @returns TRUE = daemonized
249 @returns FALSE = not daemonized
252 *///=========================================================================
253 bool detached() noexcept {
254 return __rthread_detached;
255 }; // -x- bool detached -x-
257 /*======================================================================*//**
259 Join this rthread to the current thread that called this method. (This is
260 how non-daemonized threads are normally terminated.)
262 This method blocks until this rthread's underlying pthread is terminated.
264 This method is thread-safe.
266 @throws randolf::rex::xEDEADLK Deadlock detected because two threads are
267 queued to join with each other, or the current rthread is trying to
269 @throws randolf::rex::xEINVAL Not a joinable rthread
270 @throws randolf::rex::xEINVAL A different thread is already queued to join
272 @throws randolf::rex::xESRCH A pthread with the underlying @c pthread_id
273 couldn't be found (underlying pthread doesn't exist)
275 @returns The same rthread object so as to facilitate stacking
277 *///=========================================================================
279 if (__rthread_running) {
280 __rthread_running = false; // Do this before pthread_join to signal an immediate shutdown
281 __rc_check_pthread(pthread_join(__rthread_pthread_id, NULL));
282 __rthread_detached = true; // TODO: Determine if this should actually be set to FALSE
283 } // -x- if __rthread_running -x-
285 }; // -x- rthread* join -x-
287 /*======================================================================*//**
289 Find out what the underlying @c pthread_id is.
291 Advanced developers may want easy access to this ID for a variety of reasons.
294 This method is not thread-safe.
296 @returns ID number of underlying pthread (0 = not assigned, which is what you
297 should expect to find if this rthread didn't @ref start() yet)
298 *///=========================================================================
299 pthread_t pthread_id() noexcept {
300 return __rthread_pthread_id;
301 }; // -x- pthread_t pthread_id -x-
303 /*======================================================================*//**
305 Find out whether this rthread can be re-used.
307 This method is thread-safe.
308 @returns TRUE = re-useable
309 @returns FALSE = not re-useable
310 *///=========================================================================
311 bool reuseable() noexcept {
312 return __rthread_reuseable;
313 }; // -x- bool reuseable -x-
315 /*======================================================================*//**
317 Configure whether this rthread can be re-used.
319 This method is thread-safe.
320 @returns The same rthread object so as to facilitate stacking
321 @see _rthread_reinitialize
322 *///=========================================================================
324 /// TRUE = Set this rthread to be re-useable@n
325 /// FALSE = Set this rthread to not be re-useable
326 bool flag) noexcept {
327 __rthread_reuseable = flag;
329 }; // -x- rthread* reuseable -x-
331 /*======================================================================*//**
333 Thread functionality (subclassing this method is required).
335 Do not call this method directly. To properly begin rthread execution, use
336 either of the @ref start() or @ref start_detached() methods.
337 When subclassing rthread, you need to override this method with the code that
338 is to be executed as a separate thread. (You don't have to move all of your
339 code into this method; in fact, you can simply use this method to call out to
340 code elsewhere, or call methods on instantiated classes that were referenced
341 during the instantiation of your overriding rthread() constructor, etc.)
343 Minimally, this is the only method that's required when sub-classing rthread.
348 *///=========================================================================
349 virtual void run() = 0; // Not requiring this method in the subclass is completely and utterly pointless
351 /*======================================================================*//**
353 Find out how many times this rthread was started.
354 This method is only really meaningful for @ref reuseable rthreads.
356 This method is thread-safe.
358 @see _rthread_reinitialize
360 *///=========================================================================
361 ulong run_count() noexcept {
362 return __rthread_used;
363 }; // -x- ulong run_count -x-
365 /*======================================================================*//**
367 Find out whether this rthread is actively running.
369 This method is thread-safe.
370 @returns TRUE = running
371 @returns FALSE = not running
374 *///=========================================================================
375 bool running() noexcept {
376 return __rthread_running;
377 }; // -x- bool running -x-
379 /*======================================================================*//**
381 Commence execution of the @c run() method as a separate rthread.
383 This method is thread-safe.
385 @throws randolf::rex::xEWOULDBLOCK (xEAGAIN) Insufficient resources to start
386 the underlying pthread
387 @throws randolf::rex::xEWOULDBLOCK (xEAGAIN) Maximum number-of-threads limit
390 @returns The same rthread object so as to facilitate stacking
395 *///=========================================================================
397 __rc_check_pthread(pthread_create(&__rthread_pthread_id, NULL, __rthread_run, this));
398 __rthread_used++; // Increment thread run count
400 }; // -x- rsocket* start -x-
402 /*======================================================================*//**
404 Commence execution of the @c run() method as a separate thread in a
407 This method is thread-safe.
409 @throws randolf::rex::xEDEADLK Deadlock detected because two threads are
410 queued to join with each other, or the current rthread is trying to
412 @throws randolf::rex::xEINVAL Not a joinable rthread
413 @throws randolf::rex::xEINVAL A different thread is already queued to join
415 @throws randolf::rex::xENOMEM Insufficient memory (on Linux this normally
416 always succeeds, but there's not guarantee as the community suggests
417 that this could change in the future)
418 @throws randolf::rex::xESRCH A pthread with the underlying @c pthread_id
419 couldn't be found (underlying pthread doesn't exist)
421 @returns The same rthread object so as to facilitate stacking
426 *///=========================================================================
427 rthread* start_detached() { // Use this instead of calling detach() separately to prevent the highly improbable instance of detaching a thread after it already finished
429 __rc_check_pthread(pthread_attr_init(&attr)); // Overwrite contents of "attr" structure
430 __rc_check_pthread(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED));
431 __rc_check_pthread(pthread_create(&__rthread_pthread_id, &attr, __rthread_run, this));
432 __rthread_detached = true;
433 __rthread_used++; // Increment thread run count
435 }; // -x- rthread* start_detached -x-
437 /*======================================================================*//**
439 Request the graceful termination of this rthread.
441 One side-effect of this method is to daemonize this rthread because stop()
442 serves as an alternative to the @ref join() method.
444 It is the responsibility of developers to include periodic checks throughout
445 their code (assumedly at convenient points, which is common) by utilizing the
446 @ref running() method to determine whether to start winding things down.
448 This method is thread-safe.
450 @throws randolf::rex::xEINVAL Not a joinable rthread
451 @throws randolf::rex::xESRCH A pthread with the underlying @c pthread_id
452 couldn't be found (underlying pthread doesn't exist)
454 @returns The same rthread object so as to facilitate stacking
458 *///=========================================================================
459 rthread* stop() noexcept { // This doesn't cancel the thread; it just indicates that it needs to stop running -- it's up to the code in the subclassed run() method to check periodically if it should stop by using the running() method
460 if (__rthread_running) {
462 __rthread_running = false;
463 }// -x- if __rthread_running -x-
465 }; // -x- rthread* stop -x-
468 /*======================================================================*//**
470 This internal method starts the underlying pthread, and does the following:
472 1. catches any exceptions that the thread might have thrown (and, if any
473 were caught, in turn calls the @ref exceptions() method)
475 2. if this rthread is reuseable, makes preparations for re-use, including
476 calling the re-constructor method (if it was subclassed)
478 3. if this rthreads is not reuseable, affect its destruction
481 This method is thread-safe.
482 *///=========================================================================
483 static void* __rthread_run(
484 // Pointer to subclassed rthread object, which @c pthread_create() passes as type @c void*
485 void* arg) noexcept {
487 // --------------------------------------------------------------------------
488 // Alias (void*)arg to (rthread*)r so we can just write r-> instead of having
489 // write ((rthread*)arg)-> repeatedly (the compiler will effectively do this
491 // --------------------------------------------------------------------------
492 rthread* r = (rthread*)arg;
494 // --------------------------------------------------------------------------
495 // Indicate that this rthread is running.
497 // We must set this before starting the underlying thread to avoid a
498 // potential race condition if there's a loop within the thread that first
499 // checks whether the thread is in a running state.
500 // --------------------------------------------------------------------------
501 r->__rthread_running = true; // This will be set to false in the destructor (or the reinitiator)
503 // --------------------------------------------------------------------------
504 // Call the subclassed run() method.
505 // --------------------------------------------------------------------------
508 } catch (std::exception* e) { // Handle a known exception
509 r->_rthread_exceptions(e);
510 } catch (...) { // Handle an unknown exception
511 r->_rthread_exceptions(nullptr);
514 // --------------------------------------------------------------------------
515 // This is where it becomes possible to reuse an rthread. The amount of work
516 // required to just terminate a non-reusable (default) rthread is very little
517 // compared to preparing an rthread to be reuseable at this point, but the
518 // trade-off is worthwhile when performing a minimal (and probably partial)
519 // re-initialization whilst also avoiding re-instantiating an rthread object.
520 // --------------------------------------------------------------------------
521 if (r->__rthread_reuseable) { // This rthread is reuseable
522 r->__rthread_detached = false; // Reset internal flags because each thread will begin as not-detached
523 r->__rthread_running = false; // Clear the "running" status
525 r->_rthread_reinitialize();
526 } catch (std::exception* e) { // Handle a known exception
527 r->_rthread_exceptions(e);
528 } catch (...) { // Handle an unknown exception
529 r->_rthread_exceptions(nullptr);
532 // --------------------------------------------------------------------------
533 // If an rthread is not flagged as re-useable, then it needs to be deleted.
534 // --------------------------------------------------------------------------
535 } else { // This rthread is not reuseable
536 delete r; // Initiate destructor(s) since rthread is not reuseable
537 } // -x- if __rthread_reuseable -x-
539 return r; // Same as "return arg;" but in this case we're expressing intent by returning "r"
540 }; // -x- void* __rthread_run -x-
542 }; // -x- class rthread -x-
544} // -x- namespace randolf -x-