Fawkes API Fawkes Development Version
thread.cpp
1
2/***************************************************************************
3 * thread.cpp - implementation of threads, based on pthreads
4 *
5 * Created: Thu Sep 14 13:26:39 2006
6 * Copyright 2006-2009 Tim Niemueller [www.niemueller.de]
7 *
8 ****************************************************************************/
9
10/* This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version. A runtime exception applies to
14 * this software (see LICENSE.GPL_WRE file mentioned below for details).
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Library General Public License for more details.
20 *
21 * Read the full text in the LICENSE.GPL_WRE file in the doc directory.
22 */
23
24#include <core/exceptions/software.h>
25#include <core/exceptions/system.h>
26#include <core/threading/barrier.h>
27#include <core/threading/mutex.h>
28#include <core/threading/mutex_locker.h>
29#include <core/threading/read_write_lock.h>
30#include <core/threading/thread.h>
31#include <core/threading/thread_finalizer.h>
32#include <core/threading/thread_loop_listener.h>
33#include <core/threading/thread_notification_listener.h>
34#include <core/threading/wait_condition.h>
35#include <core/utils/lock_list.h>
36
37#if defined(__gnu_linux__) && !defined(_GNU_SOURCE)
38// to get pthread_setname_np
39# define _GNU_SOURCE
40#endif
41#include <cerrno>
42#include <climits>
43#include <csignal>
44#include <cstdio>
45#include <cstdlib>
46#include <cstring>
47#include <pthread.h>
48#include <unistd.h>
49
50namespace fawkes {
51
52/** @def forever
53 * Shortcut for "while (1)".
54 * @relates Thread
55 */
56
57/** @class Thread <core/threading/thread.h>
58 * Thread class encapsulation of pthreads.
59 * This is the base class for all threads in Fawkes. Derive this class for
60 * your thread. Note that you have to set a meaningful name, as this name
61 * is necessary for easier debugging and it is used for internal messaging
62 * via the BlackBoard. Make sure that your name is unique throughout the
63 * software. Using the class name with an additional modifier if it is instantiated
64 * multiple times is a good bet.
65 *
66 * The thread can operate in two modes. The loop can either run continuously
67 * without a brake, or it can wait for an explicit wakeup after each loop.
68 * Waiting for an explicit wakeup is the default since this is the common use
69 * case in Fawkes and also it is less risky, the developer will easier see that
70 * his thread does not do anything then fixing that the thread takes all CPU time.
71 *
72 * Special care has been taken to allow for proper initialization and
73 * finalization. The special behavior of this routines can only be guaranteed
74 * if the threads are managed properly, which is the case if we speak of the
75 * Fawkes thread manager. This applies for the following paragraphs.
76 *
77 * The thread provides an init() routine which may be implemented
78 * and is called just before the thread is started. If you make use of aspects
79 * this is the first time when you can make use of aspects. These aspects
80 * are not initialized in the constructor. init() is called just after the
81 * aspect initialization. This is also the last chance to stop the thread
82 * from being executed if you detect an error. If init() throws any exception
83 * then the thread is never started.
84 *
85 * The methods prepare_finalize(), finalize() and cancel_finalize() are meant
86 * to be used for finalization. First prepare_finalize() is called to prepare
87 * finalization. At this stage the thread can veto and prevent finalization
88 * from happening. For this prepare_finalize_user() has to be implemented
89 * with the proper check, and maybe special actions that are needed to
90 * prepare finalization (which may or may not happen independent from the
91 * result of just this thread, see method description). Afterwards finalize()
92 * may be called (independent of the prepare_finalize() result, see method
93 * description). If finalize() is not executed the thread is notified with
94 * cancel_finalize(). Before finalize() is called the thread is stopped.
95 *
96 * The intialization and finalization procedures may be executed deferred and
97 * concurrent to the running thread itself. The thread is only started however
98 * it init() finished successfully.
99 *
100 * The call to prepare_finalize() is mutual exclusive with a concurrently running
101 * loop() by default. This means that if the loop() blocks waiting for some event
102 * prepare_finalize() will hang until this event happens. This can be prevented
103 * with set_prepfin_conc_loop() which allows to set that prepare_finalize() and
104 * loop() may be executed concurrently.
105 *
106 * After prepare_finalize() has been run the thread implementation will stop the
107 * loop() from being executed. However, the thread will still run, for example it will
108 * wait for wakeup. This way it can be ensured that other threads will continue
109 * to run even this thread is currently not running. An exception is the
110 * ThreadList. For this Thread provides special synchronization features by
111 * which it is possible to stop a thread in the very same loop iteration. That
112 * means that if you have two threads that are woken up at the same time and
113 * maybe even synchronize among each other it is guaranteed that both threads
114 * will finish the running loop and never enter the next loop.
115 * Before finalize() is called the thread shall be stopped (cancelled and joined).
116 *
117 * Because the finalization is done deferred and concurrent put all lengthy
118 * finalization routines in finalize() and avoid this in the destructor, since
119 * a long running destructor will harm the overall performance while with the
120 * surrounding framework a long-running finalize() is acceptable.
121 *
122 * Please read the Fawkes documentation about guarantees (FawkesGuarantees in
123 * the wiki) for information about the given guarantees. Several of these
124 * guarantees are met if Thread is used in conjunction with ThreadList and the
125 * guarantees have been specifically designed for painless plugin development.
126 *
127 * @ingroup Threading
128 * @ingroup FCL
129 * @see Aspects
130 * @see loop()
131 * @see run()
132 * @see ThreadList
133 * @see example_barrier.cpp
134 * @see example_mutex_count.cpp
135 * @see example_rwlock.cpp
136 * @see example_waitcond_serialize.cpp
137 *
138 * @author Tim Niemueller
139 */
140
141/** @var bool Thread::finalize_prepared
142 * True if prepare_finalize() has been called and was not stopped with a
143 * cancel_finalize(), false otherwise.
144 * This can also be used in finalize() to detect whether prepare_finalize() was
145 * run or not.
146 */
147
148/** @var Mutex * Thread::loop_mutex
149 * Mutex that is used to protect a call to loop().
150 * This mutex is locked just before loop() is called and unlocked right after it
151 * has finished. So you can use this lock in your derivate to make sure that a
152 * method does not run while the loop runs.
153 * For example assume that we have a method set_parameter(int x). This method may
154 * only be called if loop() is not running or unpredictable results will occur.
155 * To do this you could write the method as
156 * @code
157 * MyThread::set_parameter(int x)
158 * {
159 * loopinterrupt_antistarve_mutex->lock();
160 * loop_mutex->lock();
161 * // do what you need to do...
162 * loop_mutex->unlock();
163 * loopinterrupt_antistarve_mutex->unlock();
164 * }
165 * @endcode
166 * See documentation for loopinterrupt_antistarve_mutex why you need to use two
167 * mutexes here.
168 */
169
170/** @var Mutex * Thread::loopinterrupt_antistarve_mutex
171 * Mutex to avoid starvation when trying to lock loop_mutex.
172 * If you want to interrupt the main loop only locking loop_mutex is not enough,
173 * as this might make your try to lock it starve if the loop is running too fast
174 * (for example on a continuous thread). Because of this you always need to
175 * lock both mutexes. The anti-starve mutex will only be visited shortly and thus
176 * allows you to lock it easily. This will then block the thread from trying to
177 * lock the loop_mutex. See loop_mutex for an example.
178 */
179
180/** @fn const char * Thread::name() const
181 * Get name of thread.
182 * This name is mainly used for debugging purposes. Give it a descriptive
183 * name. Is nothing is given the raw class name is used.
184 * @return thread name
185 */
186
187/** We need not initialize this one timely by ourselves thus we do not use Mutex */
188pthread_mutex_t Thread::thread_key_mutex_ = PTHREAD_MUTEX_INITIALIZER;
189
190/** Key used to store a reference to the thread object as thread specific data. */
191pthread_key_t Thread::THREAD_KEY = PTHREAD_KEYS_MAX;
192
193#define MAIN_THREAD_NAME "MainThread"
194
195/** Standard thread flag: "thread is bad" */
196const unsigned int Thread::FLAG_BAD = 0x00000001;
197
198/** Constructor.
199 * This constructor is protected so that Thread cannot be instantiated. This
200 * constructor initalizes a few internal variables. Uses continuous
201 * operation mode.
202 * @param name thread name, used for debugging, see Thread::name()
203 */
204Thread::Thread(const char *name)
205{
206 __constructor(name, OPMODE_CONTINUOUS);
207}
208
209/** Constructor.
210 * This constructor is protected so that Thread cannot be instantiated. This
211 * constructor initalizes a few internal variables.
212 * @param name thread name, used for debugging, see Thread::name()
213 * @param op_mode Operation mode, see Thread::OpMode
214 */
215Thread::Thread(const char *name, OpMode op_mode)
216{
217 __constructor(name, op_mode);
218}
219
220/** Constructor.
221 * This constructor is protected so that Thread cannot be instantiated. This
222 * constructor initalizes a few internal variables.
223 * This is used to create a Thread wrapper instance for an existing thread.
224 * Use internally only!
225 * @param name thread name, used for debugging, see Thread::name()
226 * @param id thread ID of running thread
227 */
228Thread::Thread(const char *name, pthread_t id)
229{
230 __constructor(name, OPMODE_CONTINUOUS);
231 thread_id_ = id;
232}
233
234/** Initialize.
235 * Kind of the base constructor.
236 * @param name name of thread
237 * @param op_mode operation mode
238 */
239void
240Thread::__constructor(const char *name, OpMode op_mode)
241{
242 init_thread_key();
243
244 prepfin_conc_loop_ = false;
245 coalesce_wakeups_ = false;
246 op_mode_ = op_mode;
247 name_ = strdup(name);
248 notification_listeners_ = new LockList<ThreadNotificationListener *>();
249 loop_listeners_ = new LockList<ThreadLoopListener *>();
250
251 if (op_mode_ == OPMODE_WAITFORWAKEUP) {
252 sleep_mutex_ = new Mutex();
253 sleep_condition_ = new WaitCondition(sleep_mutex_);
254 waiting_for_wakeup_ = true;
255 } else {
256 sleep_condition_ = NULL;
257 sleep_mutex_ = NULL;
258 waiting_for_wakeup_ = false;
259 }
260
261 thread_id_ = 0;
262 flags_ = 0;
263 barrier_ = NULL;
264 started_ = false;
265 cancelled_ = false;
266 delete_on_exit_ = false;
267 prepfin_hold_ = false;
268 pending_wakeups_ = 0;
269
270 loop_mutex = new Mutex();
271 finalize_prepared = false;
272
273 loop_done_ = true;
274 loop_done_mutex_ = new Mutex();
275 loop_done_waitcond_ = new WaitCondition(loop_done_mutex_);
276
277 loopinterrupt_antistarve_mutex = new Mutex();
278 prepfin_hold_mutex_ = new Mutex();
279 prepfin_hold_waitcond_ = new WaitCondition(prepfin_hold_mutex_);
280 startup_barrier_ = new Barrier(2);
281}
282
283/** Virtual destructor. */
285{
286 loop_done_waitcond_->wake_all();
287 yield();
288
289 delete sleep_condition_;
290 delete sleep_mutex_;
291 delete loop_mutex;
292 free(name_);
293 delete notification_listeners_;
294 delete loop_listeners_;
296 delete startup_barrier_;
297 delete prepfin_hold_mutex_;
298 delete prepfin_hold_waitcond_;
299 delete loop_done_waitcond_;
300 delete loop_done_mutex_;
301}
302
303/** Copy constructor is NOT supported.
304 * Using this constructor will cause havoc and chaos. It's only here
305 * as private constructor to hide it! Therefore if you ever use it
306 * internally it will always throw an exception.
307 * @param t thread to copy.
308 * @exception Exception Always thrown
309 */
310Thread::Thread(const Thread &t)
311{
312 throw Exception("You may not use copy constructor of class Thread");
313}
314
315/** Assignment is not allowed.
316 * You may not assign one thread to another.
317 * @param t thread to assign
318 */
319Thread &
320Thread::operator=(const Thread &t)
321{
322 throw Exception("You may not use assignment operator of class Thread");
323}
324
325/** Initialize the thread.
326 * This method is meant to be used in conjunction with aspects. Some parts
327 * of the initialization may only happen after some aspect of the thread has
328 * been initialized. Implement the init method with these actions. It is
329 * guaranteed to be called just after all aspects have been initialized
330 * and only once in the lifetime of the thread.
331 * Throw an exception if any problem occurs and the thread should not run.
332 *
333 * Just because your init() routine suceeds and everything looks fine for
334 * this thread does not automatically imply that it will run. If it belongs
335 * to a group of threads in a ThreadList and any of the other threads fail
336 * to initialize then no thread from this group is run and thus this thread
337 * will never run. In that situation finalize() is called for this very
338 * instance, prepare_finalize() however is not called.
339 *
340 * @see Aspects
341 */
342void
344{
345}
346
347/** Prepare finalization.
348 * Check if finalization at this point is possible and if so execute the
349 * steps necessary to prepare for finalization. You also have to make sure
350 * that this state of being able to finalize does not change until either
351 * finalize() or cancel_finalize() is called.
352 *
353 * This method may return false, which means that at this point the thread
354 * cannot be stopped safely. This might be due to a critical internal
355 * condition that may hurt hardware if turned of right now. In this case
356 * a logger should be used to log the reason for the failure. The check is
357 * implemented in prepare_finalize_user(), which the user has to implement
358 * if he needs special treatment.
359 *
360 * Even if the finalization is said to be unsafe and false is returned, the
361 * caller may still decide to finalize this thread, for example if all
362 * threads are shut down on application exit. So you may not rely on the
363 * fact that the thread is not stopped if you return false.
364 *
365 * You may not override this method.
366 *
367 * It is guaranteed that this method is only called for a running thread.
368 *
369 * @return true if the thread can be stopped and destroyed safely, false if
370 * it has to stay alive
371 * @see finalize()
372 * @see cancel_finalize()
373 */
374bool
376{
377 if (!started_) {
378 throw CannotFinalizeThreadException("Thread has not been started");
379 }
380 if (finalize_prepared) {
381 throw CannotFinalizeThreadException("prepare_finalize() has already been called");
382 }
383 prepfin_hold_mutex_->lock();
384 while (prepfin_hold_) {
385 prepfin_hold_waitcond_->wait();
386 }
387 if (!prepfin_conc_loop_) {
389 loop_mutex->lock();
390 }
391 finalize_prepared = true;
392 bool prepared = prepare_finalize_user();
393 if (!prepfin_conc_loop_) {
396 }
397 prepfin_hold_mutex_->unlock();
398 return prepared;
399}
400
401/** Prepare finalization user implementation.
402 * This method is called by prepare_finalize(). If there can ever be a
403 * situation where it is not safe to turn of a thread at some point in
404 * time then implement this method to determine these unsafe states.
405 *
406 * An example that comes to my mind is our Katana arm. If you turn it off
407 * it looses all power and collapses back upon itself. This may damage the
408 * arm if it is not in a safe position. In this situation this method would
409 * return false to indicate this problem.
410 *
411 * It is up to the user to decide if this should be taken for an implied
412 * signal to get in such a safe state, if this is possible at all.
413 *
414 * This feature should be used rarely as it can have tremendous implications
415 * on the performance and experience of the whole software. In any case your
416 * implementation should somehow inform the user of the problem that caused
417 * the finalization to fail. If you are using aspect use the LoggerAspect and
418 * log the reason.
419 *
420 * The default implementation always allows finalization.
421 * @return true, if the thread can be finalized, false otherwise.
422 */
423bool
425{
426 return true;
427}
428
429/** Finalize the thread.
430 * This method is executed just before the thread is canceled and destroyed.
431 * It is always preceeded by a call to prepare_finalize(). If this is not
432 * the case this is a failure. The condition can be checked with
433 * the boolean variable finalize_prepared.
434 *
435 * This method is meant to be used in conjunction with aspects and to cover
436 * thread inter-dependencies. This routine MUST bring the thread into a safe
437 * state such that it may be canceled and destroyed afterwards. If there is
438 * any reason that this cannot happen make your prepare_finalize() reports so.
439 *
440 * This method is called by the thread manager just before the thread is
441 * being cancelled. Here you can do whatever steps are necessary just before
442 * the thread is cancelled. Note that you thread is still running and might
443 * be in the middle of a loop, so it is not a good place to give up on all
444 * resources used. Mind segmentation faults that could happen. Protect the
445 * area with a mutex that you lock at the beginning of your loop and free
446 * in the end, and that you lock at the beginning of finalize and then never
447 * unlock. Also not that the finalization may be canceled afterwards. The
448 * next thing that happens is that either the thread is canceled and destroyed
449 * or that the finalization is canceled and the thread has to run again.
450 *
451 * Finalize is called on a thread just before it is deleted. It is guaranteed
452 * to be called on a fully initialized thread (if no exception is thrown in
453 * init()) (this guarantee holds in the Fawkes framework).
454 *
455 * The default implementation does nothing besides throwing an exception if
456 * prepare_finalize() has not been called.
457 *
458 * @exception Exception thrown if prepare_finalize() has not been called.
459 * @see prepare_finalize()
460 * @see cancel_finalize()
461 */
462void
464{
465}
466
467/** Cancel finalization.
468 * This means that something has happened (for example another thread from
469 * the same plugin) has indicated that it can not be finalized. In that case
470 * also this thread has to continue to run and the finalization is canceled.
471 * The thread is expected to run after the finalization has been canceled as
472 * if the finalization was never tried.
473 *
474 * This is only called on a running thread after prepare_finalization() has
475 * been called.
476 *
477 * @see prepare_finalize()
478 * @see finalize()
479 */
480void
482{
483 if (!started_) {
484 throw CannotFinalizeThreadException("Cannot cancel finalize, thread has not been started");
485 }
486 loop_mutex->lock();
487 finalize_prepared = false;
489}
490
491/** Call this method to start the thread.
492 * This method has to be called after the thread has been instantiated and
493 * initialized to start it. To meet the Fawkes guarantees you this may only
494 * be called if the initialization of the thread has been successful.
495 * @param wait if true this method will block until the thread is really
496 * started, otherwise it will only initiate the startup and return immediately
497 */
498void
500{
501 int err;
502 if (started_) {
503 throw Exception("You cannot start the same thread twice!");
504 }
505
506 cancelled_ = false;
507 detached_ = false;
508 started_ = true;
509 wait_ = wait;
510
511 if ((err = pthread_create(&thread_id_, NULL, Thread::entry, this)) != 0) {
512 // An error occured
513 throw Exception("Could not start thread", err);
514 }
515#if defined(_GNU_SOURCE) && defined(__GLIBC__) \
516 && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 12) || __GLIBC__ > 2)
517 char tmpname[16];
518 strncpy(tmpname, name_, 15);
519 tmpname[15] = 0;
520 pthread_setname_np(thread_id_, tmpname);
521#endif
522
523 if (wait_)
524 startup_barrier_->wait();
525}
526
527void
528Thread::lock_sleep_mutex()
529{
530 if (sleep_mutex_) {
531 sleep_mutex_->lock();
532 }
533}
534
535/** Entry point for the thread.
536 * This is an utility method that acts as an entry point to the thread.
537 * It is called automatically when you start the thread and will call run()
538 * @param pthis a pointer to the instance that triggered the run of this method
539 */
540/* static */ void *
541Thread::entry(void *pthis)
542{
543 Thread *t = (Thread *)pthis;
544
545 // Can be used for easier debugging in gdb, need to make this accessible
546 // printf("Thread %s (%lu) started\n", t->name(), t->thread_id());
547
548 // Set thread instance as TSD
549 set_tsd_thread_instance(t);
550
551 // lock sleep mutex, needed such that thread waits for initial wakeup
552 t->lock_sleep_mutex();
553
554 // Notify listeners that this thread started
555 t->notify_of_startup();
556
557 // Thread is started now, thread that called start() will continue
558 if (t->wait_)
559 t->startup_barrier_->wait();
560
561 // Run thread
562 t->loop_mutex->lock();
563 t->once();
564 t->loop_mutex->unlock();
565 t->run();
566
567 if (t->detached_) {
568 // mark as stopped if detached since the thread will be deleted
569 // after entry() is done
570 t->started_ = false;
571 }
572
573 // have no useful exit value
574 return NULL;
575}
576
577/** Exit the thread.
578 * You may call this from within your run() method to exit the thread.
579 * @see run()
580 */
581void
583{
584 if (delete_on_exit_) {
585 delete this;
586 }
587
588 waiting_for_wakeup_ = false;
589 cancelled_ = true;
590 pthread_exit(NULL);
591}
592
593/** Join the thread.
594 * This waites for the thread to exit.
595 */
596void
598{
599 if (started_) {
600 void *dont_care;
601 pthread_join(thread_id_, &dont_care);
602 started_ = false;
603
604 if (sleep_mutex_ != NULL) {
605 // We HAVE to release this sleep mutex under any circumstances, so we try
606 // to lock it (locking a locked mutex or unlocking and unlocked mutex are undefined)
607 // and then unlock it. This is for example necessary if a thread is cancelled, and
608 // then set_opmode() is called, this would lead to a deadlock if the thread was
609 // cancelled while waiting for the sleep lock (which is very likely)
610 sleep_mutex_->try_lock();
611 sleep_mutex_->unlock();
612 }
613
614 // Force unlock of these mutexes, otherwise the same bad things as for the sleep
615 // mutex above could happen!
618
619 // Force unlock of the loop listeners' mutex. If the thread is canceled
620 // during a loop listener call (pre_loop or post_loop), the thread cannot
621 // be finalized because this LockList is still locked, and any aspect using
622 // a LoopListener will try to remove itself from the LockList during
623 // finalization, leading to a deadlock. It is safe to unlock the mutex
624 // because the thread is already joined and thus no more loop listener calls
625 // will occur.
626 loop_listeners_->try_lock();
627 loop_listeners_->unlock();
628 }
629}
630
631/** Detach the thread.
632 * Memory claimed by the thread will be automatically freed after the
633 * thread exits. You can no longer join this thread.
634 */
635void
637{
638 detached_ = true;
639 pthread_detach(thread_id_);
640}
641
642/** Cancel a thread.
643 * Use this to cancel the thread.
644 */
645void
647{
648 if (started_ && !cancelled_) {
649 if (pthread_cancel(thread_id_) == 0) {
650 waiting_for_wakeup_ = false;
651 cancelled_ = true;
652 }
653 }
654}
655
656/** Send signal to a thread.
657 * Not that sending an unhandled signal might kill the whole process, not just the
658 * thread!
659 * @param sig signal to send.
660 */
661void
663{
664 pthread_kill(thread_id_, sig);
665}
666
667/** Get operation mode.
668 * @return opmode of thread.
669 */
672{
673 return op_mode_;
674}
675
676/** Set operation mode.
677 * This can be done at any time and the thread will from the next cycle on
678 * run in the new mode.
679 * @param op_mode new operation mode
680 */
681void
683{
684 if (started_) {
685 throw Exception("Cannot set thread opmode while running");
686 }
687
688 if ((op_mode_ == OPMODE_WAITFORWAKEUP) && (op_mode == OPMODE_CONTINUOUS)) {
689 op_mode_ = OPMODE_CONTINUOUS;
690 delete sleep_condition_;
691 delete sleep_mutex_;
692 sleep_condition_ = NULL;
693 sleep_mutex_ = NULL;
694 } else if ((op_mode_ == OPMODE_CONTINUOUS) && (op_mode == OPMODE_WAITFORWAKEUP)) {
695 sleep_mutex_ = new Mutex();
696 sleep_condition_ = new WaitCondition(sleep_mutex_);
697 op_mode_ = OPMODE_WAITFORWAKEUP;
698 }
699}
700
701/** Set concurrent execution of prepare_finalize() and loop().
702 * Usually calls to prepare_finalize() and a running loop() are mutually exclusive.
703 * The prepare_finalize() call will wait for the current loop() run to finish before
704 * calling the user implementation. If you have a thread that blocks in its loop for
705 * example in a blocking system call this would lead to a dead-lock if no condition
706 * that makes the loop finish occurs. For this reason this method has been added.
707 * If you set this to true then prepare_finalize() can be executed concurrent to
708 * a running loop() call. If this is critical for parts of loop() you have to
709 * protect the critical sections by yourself. Use this sparsely and be sure you really
710 * know what you are doing. This method is necessary in some situations and powerful
711 * if used wisely. By default a thread will enforce mutual exclusion.
712 * @param concurrent true to allow concurrent execution of prepare_finalize() and loop(),
713 * false to enforce mutual exclusion (the latter being the default)
714 */
715void
717{
718 prepfin_conc_loop_ = concurrent;
719}
720
721/** Set wakeup coalescing.
722 * The standard behavior of multiple calls to wakeup() (before the thread actually
723 * got woken up, for instance because a loop iteration was still running) is to
724 * execute one iteration for each wakeup. When setting coalescing, multiple calls
725 * will only cause a single execution of the loop.
726 * @param coalesce true to coalesce wakeups, false to keep the original behavior
727 */
728void
730{
731 if (op_mode_ == OPMODE_CONTINUOUS) {
732 // nothing is using the value, just write it
733 coalesce_wakeups_ = coalesce;
734 } else {
735 // protect usage for calls to wakeup()
736 MutexLocker lock(sleep_mutex_);
737 coalesce_wakeups_ = coalesce;
738 }
739}
740
741/** Set name of thread.
742 * If you want a more descriptive thread name you can do so by calling this method
743 * in your thread's constructor, and only in the constructor.
744 * Use parameters similar to printf().
745 * @param format format string
746 */
747void
748Thread::set_name(const char *format, ...)
749{
750 va_list va;
751 va_start(va, format);
752 char *old_name = name_;
753 if (vasprintf(&name_, format, va) == -1) {
754 name_ = old_name;
755 throw OutOfMemoryException("Could not set new thread name for '%s'", name_);
756 } else {
757 free(old_name);
758 }
759 va_end(va);
760#if defined(_GNU_SOURCE) && defined(__GLIBC__) \
761 && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 12) || __GLIBC__ > 2)
762 if (thread_id_) {
763 char tmpname[16];
764 strncpy(tmpname, name_, 15);
765 tmpname[15] = 0;
766 pthread_setname_np(thread_id_, tmpname);
767 }
768#endif
769}
770
771/** Hold prepare_finalize().
772 * In some situations you have to hold the finalization of a thread up to a certain
773 * safe point. With set_prepfin_hold() you can do this. If you set \p hold to true
774 * then a call to \c prepare_finalize() will block until \c set_prepfin_hold(false)
775 * is called.
776 * @param hold true to hold next call to \c prepare_finalize(), false to release it
777 * @exception Exception thrown if \c prepare_finalize() has already been called before
778 * trying to set \p hold to true.
779 */
780void
782{
783 prepfin_hold_mutex_->lock();
784 if (hold && finalize_prepared) {
785 prepfin_hold_mutex_->unlock();
786 throw Exception("Thread(%s)::set_prepfin_hold: prepare_finalize() has "
787 "been called already()",
788 name_);
789 }
790 prepfin_hold_ = hold;
791 if (!hold) {
792 prepfin_hold_waitcond_->wake_all();
793 }
794 prepfin_hold_mutex_->unlock();
795}
796
797/** Get ID of thread.
798 * @return thread ID
799 */
800pthread_t
802{
803 return thread_id_;
804}
805
806/** Check if thread has been started.
807 * @return true if thread has been started, false otherwise
808 */
809bool
811{
812 return started_;
813}
814
815/** Check if thread has been cancelled.
816 * @return true if the thread has been cancelled, false otherwise
817 */
818bool
820{
821 return cancelled_;
822}
823
824/** Check if thread has been detached.
825 * @return true if the thread has been detached, false otherwise
826 */
827bool
829{
830 return detached_;
831}
832
833/** Check if the thread is running.
834 * A thread is running if it currently is busy in its loop() or once() method.
835 * @return true if the thread is running, false otherwise
836 */
837bool
839{
840 // loop_mutex is mutable and thus we can call the lock methods here
841 if (loop_mutex->try_lock()) {
843 return false;
844 } else {
845 return true;
846 }
847}
848
849/** Check if thread is currently waiting for wakeup.
850 * A continuous thread is never waiting for wakeup and thus will always return
851 * false. A wait-for-wakeup thread is waiting when it has passed the wakeup
852 * barrier (if supplied) and is now waiting for the next call to wakeup()
853 * to run again.
854 * @return true if the thread is waiting, false otherwise
855 */
856bool
858{
859 if (op_mode_ != OPMODE_WAITFORWAKEUP) {
860 return false;
861 } else {
862 MutexLocker lock(sleep_mutex_);
863 return waiting_for_wakeup_;
864 }
865}
866
867/** Set cancellation point.
868 * Tests if the thread has been canceled and if so exits the thread.
869 */
870void
872{
873 pthread_testcancel();
874}
875
876/** Yield the processor to another thread or process.
877 * This will suspend the execution of the current thread in favor of other
878 * threads. The thread will then be re-scheduled for later execution.
879 * Use this method to make sure that other threads get a chance to get the CPU
880 * for example if your thread is waiting for results from other threads.
881 */
882void
884{
885#ifdef __USE_GNU
886 pthread_yield();
887#else
888 usleep(0);
889#endif
890}
891
892/** Check if two threads are the same.
893 * @param thread Thread to compare this thread to.
894 * @return true, if the threads are equal, false otherwise.
895 */
896bool
898{
899 return (pthread_equal(thread_id_, thread.thread_id_) != 0);
900}
901
902/** Code to execute in the thread.
903 * Executes loop() in each cycle. This is the default implementation and if
904 * you need a more specific behaviour you can override this run() method and
905 * ignore loop().
906 * Although this method is declared virtual, it should not be overridden, other
907 * than with the following trivial snippet:
908 * @code
909 * protected: virtual void run() { Thread::run(); }
910 * @endcode
911 * The reason not to do other changes is that it contains complex house keeping
912 * code that the system relies on. The reason for still allowing the override is
913 * solely to make reading back traces in your debugger easier. Because now there
914 * the class name of the thread sub-class will appear in the back trace, while
915 * it would not otherwise.
916 */
917void
919{
920 if (op_mode_ == OPMODE_WAITFORWAKEUP) {
921 // Wait for initial wakeup
922 // sleep_mutex_ has been locked in entry() already!
923 while (pending_wakeups_ == 0) {
924 waiting_for_wakeup_ = true;
925 sleep_condition_->wait();
926 }
927 pending_wakeups_ -= 1;
928 sleep_mutex_->unlock();
929 }
930
931 forever
932 {
934
935 if (!finalize_prepared) {
936 loop_done_ = false;
937
938 loop_listeners_->lock();
939 for (LockList<ThreadLoopListener *>::iterator it = loop_listeners_->begin();
940 it != loop_listeners_->end();
941 it++) {
942 (*it)->pre_loop(this);
943 }
944 loop_listeners_->unlock();
945
946 loop_mutex->lock();
947 loop();
949
950 loop_listeners_->lock();
951 for (LockList<ThreadLoopListener *>::reverse_iterator it = loop_listeners_->rbegin();
952 it != loop_listeners_->rend();
953 it++) {
954 (*it)->post_loop(this);
955 }
956 loop_listeners_->unlock();
957 }
958
959 loop_done_mutex_->lock();
960 loop_done_ = true;
961 loop_done_mutex_->unlock();
962 loop_done_waitcond_->wake_all();
963
964 test_cancel();
965 if (op_mode_ == OPMODE_WAITFORWAKEUP) {
966 if (barrier_) {
967 sleep_mutex_->lock();
968 Barrier *b = barrier_;
969 barrier_ = NULL;
970 sleep_mutex_->unlock();
971
972 b->wait();
973
974 sleep_mutex_->lock();
975 } else {
976 sleep_mutex_->lock();
977 }
978
979 while (pending_wakeups_ == 0) {
980 waiting_for_wakeup_ = true;
981 sleep_condition_->wait();
982 }
983 pending_wakeups_ -= 1;
984 sleep_mutex_->unlock();
985 }
986 yield();
987 }
988}
989
990/** Wake up thread.
991 * If the thread is being used in wait for wakeup mode this will wake up the
992 * waiting thread.
993 */
994void
996{
997 if (op_mode_ == OPMODE_WAITFORWAKEUP) {
998 MutexLocker lock(sleep_mutex_);
999
1000 if (barrier_) {
1001 throw Exception("Thread(%s): wakeup() cannot be called if loop is running "
1002 "with barrier already",
1003 name_);
1004 }
1005
1006 if (coalesce_wakeups_)
1007 pending_wakeups_ = 1;
1008 else
1009 pending_wakeups_ += 1;
1010 if (waiting_for_wakeup_) {
1011 // currently waiting
1012 waiting_for_wakeup_ = false;
1013 sleep_condition_->wake_all();
1014 }
1015 }
1016}
1017
1018/** Wake up thread and wait for barrier afterwards.
1019 * If the thread is being used in wait for wakeup mode this will wake up the
1020 * waiting thread. Additionally after the loop is finished
1021 * @param barrier barrier to wait for after loop
1022 */
1023void
1025{
1026 if (op_mode_ != OPMODE_WAITFORWAKEUP)
1027 return;
1028
1029 if (barrier == NULL) {
1030 throw NullPointerException("Thread(%s)::wakeup(): barrier must not be NULL", name_);
1031 }
1032
1033 MutexLocker lock(sleep_mutex_);
1034 if (!waiting_for_wakeup_ && barrier_) {
1035 throw Exception("Thread %s already running with barrier, cannot wakeup %i %p",
1036 name_,
1037 waiting_for_wakeup_,
1038 barrier_);
1039 }
1040
1041 pending_wakeups_ += 1;
1042 barrier_ = barrier;
1043 if (waiting_for_wakeup_) {
1044 // currently waiting
1045 waiting_for_wakeup_ = false;
1046 sleep_condition_->wake_all();
1047 }
1048}
1049
1050/** Wait for the current loop iteration to finish. */
1051void
1053{
1054 loop_done_mutex_->lock();
1055 while (!loop_done_) {
1056 loop_done_waitcond_->wait();
1057 }
1058 loop_done_mutex_->unlock();
1059}
1060
1061/** Code to execute in the thread.
1062 * Implement this method to hold the code you want to be executed continously.
1063 * If you do not implement this method, the default is that the thread will exit.
1064 * This is useful if you choose to only implement once().
1065 */
1066void
1068{
1069 if (delete_on_exit_) {
1070 delete this;
1071 }
1072 loop_mutex->unlock();
1073 pthread_exit(NULL);
1074}
1075
1076/** Execute an action exactly once.
1077 * This code is executed once and only once right after the thread is started
1078 * before loop() is called.
1079 * This is useful if you want to implement an one-shot background job. Just implement
1080 * once() and leave loop() untouched. Start the thread and detach it and it will just
1081 * do its job and then die automatically. If you use set_delete_on_exit(true) even the
1082 * Thread instance will be automatically deleted.
1083 */
1084void
1086{
1087}
1088
1089/** Set whether the thread should be deleted on exit.
1090 * If you set this to true the thread instance is deleted if the threads exits
1091 * (only on internal exits, not if you cancel the thread!).
1092 * This is particularly useful if you only implement once() and not loop().
1093 * @param del true to delete thread on exit, false otherwise
1094 */
1095void
1097{
1098 delete_on_exit_ = del;
1099}
1100
1101/** Check if wakeups are pending.
1102 * @return true if at least one more loop iteration has been queued (wakeup() has
1103 * been called), false otherwise
1104 */
1105bool
1107{
1108 MutexLocker lock(sleep_mutex_);
1109 return (pending_wakeups_ > 0);
1110}
1111
1112/** Set flag for the thread.
1113 * The first two bytes of the flags are reserved for custom usage from the outside
1114 * and they are never used internally. The last two bytes are used to indicate
1115 * internal states, like flagging a thread as bad (timing was not ok). Setting
1116 * the latter bits may have influence on the inner workings on the thread and
1117 * thus should only be done if you really know what you are doing.
1118 * @param flag flag to set
1119 * @see set_flags()
1120 */
1121void
1122Thread::set_flag(uint32_t flag)
1123{
1124 flags_ |= flag;
1125}
1126
1127/** Unset flag.
1128 * Unsets a specified flag.
1129 * @param flag flag to unset
1130 * @see set_flag()
1131 */
1132void
1134{
1135 flags_ &= 0xFFFFFFFF ^ flag;
1136}
1137
1138/** Set all flags in one go.
1139 * @param flags flags
1140 */
1141void
1142Thread::set_flags(uint32_t flags)
1143{
1144 flags_ = flags;
1145}
1146
1147/** Check if FLAG_BAD was set.
1148 * This is a convenience method to check if FLAG_BAD has been set.
1149 * @return true if flag is set, false otherwise
1150 */
1151bool
1153{
1154 return flags_ & FLAG_BAD;
1155}
1156
1157/** Add notification listener.
1158 * Add a notification listener for this thread.
1159 * @param notification_listener notification listener to add
1160 */
1161void
1163{
1164 notification_listeners_->push_back_locked(notification_listener);
1165}
1166
1167/** Remove notification listener.
1168 * @param notification_listener notification listener to remove
1169 */
1170void
1172{
1173 notification_listeners_->remove_locked(notification_listener);
1174}
1175
1176/** Add loop listener.
1177 * Add a loop listener for this thread.
1178 * @param loop_listener loop listener to add
1179 */
1180void
1182{
1183 loop_listeners_->push_back_locked(loop_listener);
1184}
1185
1186/** Remove loop listener.
1187 * @param loop_listener loop listener to remove
1188 */
1189void
1191{
1192 loop_listeners_->remove_locked(loop_listener);
1193}
1194
1195/** Notify of successful startup.
1196 * This method is called internally in entry().
1197 */
1198void
1199Thread::notify_of_startup()
1200{
1201 notification_listeners_->lock();
1202 LockList<ThreadNotificationListener *>::iterator i = notification_listeners_->begin();
1203 while (i != notification_listeners_->end()) {
1204 if (!(*i)->thread_started(this)) {
1205 i = notification_listeners_->erase(i);
1206 } else {
1207 ++i;
1208 }
1209 }
1210 notification_listeners_->unlock();
1211}
1212
1213/** Notify of failed init.
1214 * This method must be called if the initialization of the thread
1215 * failed, e.g. in a thread collector. Do not use it arbitrarily!
1216 */
1217void
1219{
1220 notification_listeners_->lock();
1221 LockList<ThreadNotificationListener *>::iterator i = notification_listeners_->begin();
1222 while (i != notification_listeners_->end()) {
1223 if (!(*i)->thread_init_failed(this)) {
1224 i = notification_listeners_->erase(i);
1225 } else {
1226 ++i;
1227 }
1228 }
1229 notification_listeners_->unlock();
1230}
1231
1232/** Intialize thread key.
1233 * For internal usage only.
1234 */
1235void
1236Thread::init_thread_key()
1237{
1238 pthread_mutex_lock(&thread_key_mutex_);
1239 if (THREAD_KEY == PTHREAD_KEYS_MAX) {
1240 // Has not been initialized, do it!
1241 int err;
1242 if ((err = pthread_key_create(&THREAD_KEY, NULL)) != 0) {
1243 if (ENOMEM == err) {
1244 throw OutOfMemoryException("Could not create key for thread "
1245 "specific data (reference to thread)");
1246 } else {
1247 throw Exception("Thread key for reference to thread could not be created", err);
1248 }
1249 }
1250 }
1251 pthread_mutex_unlock(&thread_key_mutex_);
1252}
1253
1254/** Set thread instance in thread-specific data (TSD).
1255 * Use thread-specific data to store a reference to the Thread instance in the
1256 * pthread struct. Used by current_thread().
1257 * @param t thread to set specific data on
1258 */
1259void
1260Thread::set_tsd_thread_instance(Thread *t)
1261{
1262 int err = 0;
1263 if ((err = pthread_setspecific(THREAD_KEY, t)) != 0) {
1264 if (ENOMEM == err) {
1265 throw OutOfMemoryException("Could not set specific data (reference to thread)");
1266 } else {
1267 throw Exception("Could not set specific data (reference to thread), unknown reason");
1268 }
1269 }
1270}
1271
1272/** Initialize Thread wrapper instance for main thread.
1273 * This will create an internal Thread instance such that it can be guaranteed that
1274 */
1275void
1277{
1278 init_thread_key();
1279 Thread *t = new Thread(MAIN_THREAD_NAME, pthread_self());
1280 set_tsd_thread_instance(t);
1281}
1282
1283/** Destroy main thread wrapper instance.
1284 * This destroys the thread wrapper created with init_main(). Note that
1285 * this has to be called from the very same thread that init_main() was called
1286 * from, which should be the main thread (somewhere from main() on).
1287 */
1288void
1290{
1291 Thread *t = current_thread();
1292 if (strcmp(t->name(), MAIN_THREAD_NAME) == 0) {
1293 delete t;
1294 } else {
1295 throw Exception("Main thread can only be destroyed in main thread");
1296 }
1297}
1298
1299/** Get the ID of the currently running thread.
1300 * This will return the ID of the thread in which's context this method was
1301 * called.
1302 * @return ID of thread context
1303 */
1304pthread_t
1306{
1307 return pthread_self();
1308}
1309
1310/** Get the name of the current thread.
1311 * This will first check if this is a Thread instance, and if so call
1312 * name() to determine the name. Otherwise, it will check if a
1313 * system-specific name can be retrieved. If this is not the case,
1314 * returns an empty string.
1315 * @return name of thread if it cannot be determined, empty string otherwise
1316 */
1317std::string
1319{
1321 if (t) {
1322 return t->name();
1323#if defined(_GNU_SOURCE) && defined(__GLIBC__) \
1324 && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 12) || __GLIBC__ > 2)
1325 } else {
1326 char name[16];
1327 if (pthread_getname_np(pthread_self(), name, 16) == 0) {
1328 return name;
1329 }
1330#endif
1331 }
1332
1333 return "";
1334}
1335
1336/** Set the name of the current thread.
1337 * This will first check if this is a Thread instance, and if so call
1338 * set_name() to set the name. Otherwise, it will check if a
1339 * system-specific name can be set.
1340 * @param thread_name thread name to set
1341 */
1342void
1343Thread::current_thread_name(const std::string &thread_name)
1344{
1346 if (t) {
1347 return t->set_name("%s", thread_name.c_str());
1348#if defined(_GNU_SOURCE) && defined(__GLIBC__) \
1349 && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 12) || __GLIBC__ > 2)
1350 } else {
1351 pthread_setname_np(pthread_self(), thread_name.c_str());
1352#endif
1353 }
1354}
1355
1356/** Get the Thread instance of the currently running thread.
1357 * This will return the Thread instance of the thread in which's context this method was
1358 * called.
1359 * Note that only if the main application ensures to call init_main() it can be guaranteed
1360 * that this value is not NULL.
1361 * @return Thread instance of the current thread
1362 * @exception Exception thrown if this method is called before either init_main() is
1363 * called or any one thread has been started.
1364 */
1365Thread *
1367{
1368 if (THREAD_KEY == PTHREAD_KEYS_MAX) {
1369 throw Exception("No thread has been initialized");
1370 }
1371 return (Thread *)pthread_getspecific(THREAD_KEY);
1372}
1373
1374/** Similar to current_thread, but does never throw an exception.
1375 * This is a convenience method doing the same as current_thread(), but it never ever
1376 * throws an exception, rather it returns NULL in case of an error. This is necessary
1377 * if run from a C context.
1378 * @return Thread instance of the current thread
1379 */
1380Thread *
1382{
1383 if (THREAD_KEY == PTHREAD_KEYS_MAX) {
1384 return 0;
1385 }
1386 return (Thread *)pthread_getspecific(THREAD_KEY);
1387}
1388
1389/** Set the cancel state of the current thread.
1390 * The cancel state can only be set on the current thread. Please also
1391 * consider the documentation for pthread_setcancelstate().
1392 * @param new_state new cancel state
1393 * @param old_state old cancel state
1394 */
1395void
1397{
1398 int oldstate = PTHREAD_CANCEL_ENABLE;
1399 int newstate = PTHREAD_CANCEL_ENABLE;
1400 if (new_state == CANCEL_DISABLED) {
1401 newstate = PTHREAD_CANCEL_DISABLE;
1402 }
1403
1404 pthread_setcancelstate(newstate, &oldstate);
1405
1406 if (old_state != NULL) {
1407 if (oldstate == PTHREAD_CANCEL_DISABLE) {
1408 *old_state = CANCEL_DISABLED;
1409 } else {
1410 *old_state = CANCEL_ENABLED;
1411 }
1412 }
1413}
1414
1415} // end namespace fawkes
A barrier is a synchronization tool which blocks until a given number of threads have reached the bar...
Definition: barrier.h:32
virtual void wait()
Wait for other threads.
Definition: barrier.cpp:153
Thread cannot be finalized.
Base class for exceptions in Fawkes.
Definition: exception.h:36
List with a lock.
Definition: lock_list.h:45
Mutex locking helper.
Definition: mutex_locker.h:34
Mutex mutual exclusion lock.
Definition: mutex.h:33
bool try_lock()
Tries to lock the mutex.
Definition: mutex.cpp:117
void lock()
Lock this mutex.
Definition: mutex.cpp:87
void stopby()
Shortly stop by at the mutex.
Definition: mutex.cpp:150
void unlock()
Unlock the mutex.
Definition: mutex.cpp:131
A NULL pointer was supplied where not allowed.
Definition: software.h:32
System ran out of memory and desired operation could not be fulfilled.
Definition: system.h:32
Thread loop listener interface.
Thread notification listener interface.
Thread class encapsulation of pthreads.
Definition: thread.h:46
bool finalize_prepared
True if prepare_finalize() has been called and was not stopped with a cancel_finalize(),...
Definition: thread.h:151
void kill(int sig)
Send signal to a thread.
Definition: thread.cpp:662
void set_prepfin_conc_loop(bool concurrent=true)
Set concurrent execution of prepare_finalize() and loop().
Definition: thread.cpp:716
Mutex * loop_mutex
Mutex that is used to protect a call to loop().
Definition: thread.h:152
void add_loop_listener(ThreadLoopListener *loop_listener)
Add loop listener.
Definition: thread.cpp:1181
const char * name() const
Get name of thread.
Definition: thread.h:100
OpMode opmode() const
Get operation mode.
Definition: thread.cpp:671
static void destroy_main()
Destroy main thread wrapper instance.
Definition: thread.cpp:1289
void start(bool wait=true)
Call this method to start the thread.
Definition: thread.cpp:499
static void init_main()
Initialize Thread wrapper instance for main thread.
Definition: thread.cpp:1276
void unset_flag(uint32_t flag)
Unset flag.
Definition: thread.cpp:1133
static const unsigned int FLAG_BAD
Standard thread flag: "thread is bad".
Definition: thread.h:69
CancelState
Cancel state.
Definition: thread.h:64
@ CANCEL_ENABLED
cancellation is possible
Definition: thread.h:65
@ CANCEL_DISABLED
thread cannot be cancelled
Definition: thread.h:66
static void set_cancel_state(CancelState new_state, CancelState *old_state=0)
Set the cancel state of the current thread.
Definition: thread.cpp:1396
virtual ~Thread()
Virtual destructor.
Definition: thread.cpp:284
void join()
Join the thread.
Definition: thread.cpp:597
static pthread_t current_thread_id()
Get the ID of the currently running thread.
Definition: thread.cpp:1305
void yield()
Yield the processor to another thread or process.
Definition: thread.cpp:883
void set_prepfin_hold(bool hold)
Hold prepare_finalize().
Definition: thread.cpp:781
virtual bool prepare_finalize_user()
Prepare finalization user implementation.
Definition: thread.cpp:424
void wait_loop_done()
Wait for the current loop iteration to finish.
Definition: thread.cpp:1052
bool waiting() const
Check if thread is currently waiting for wakeup.
Definition: thread.cpp:857
bool running() const
Check if the thread is running.
Definition: thread.cpp:838
static Thread * current_thread_noexc() noexcept
Similar to current_thread, but does never throw an exception.
Definition: thread.cpp:1381
bool detached() const
Check if thread has been detached.
Definition: thread.cpp:828
bool started() const
Check if thread has been started.
Definition: thread.cpp:810
void set_opmode(OpMode op_mode)
Set operation mode.
Definition: thread.cpp:682
Thread(const char *name)
Constructor.
Definition: thread.cpp:204
void exit()
Exit the thread.
Definition: thread.cpp:582
void detach()
Detach the thread.
Definition: thread.cpp:636
virtual void once()
Execute an action exactly once.
Definition: thread.cpp:1085
bool prepare_finalize()
Prepare finalization.
Definition: thread.cpp:375
bool flagged_bad() const
Check if FLAG_BAD was set.
Definition: thread.cpp:1152
virtual void init()
Initialize the thread.
Definition: thread.cpp:343
void set_name(const char *format,...)
Set name of thread.
Definition: thread.cpp:748
void add_notification_listener(ThreadNotificationListener *notification_listener)
Add notification listener.
Definition: thread.cpp:1162
void wakeup()
Wake up thread.
Definition: thread.cpp:995
virtual void loop()
Code to execute in the thread.
Definition: thread.cpp:1067
void remove_loop_listener(ThreadLoopListener *loop_listener)
Remove loop listener.
Definition: thread.cpp:1190
pthread_t thread_id() const
Get ID of thread.
Definition: thread.cpp:801
void test_cancel()
Set cancellation point.
Definition: thread.cpp:871
void set_flag(uint32_t flag)
Set flag for the thread.
Definition: thread.cpp:1122
bool wakeup_pending()
Check if wakeups are pending.
Definition: thread.cpp:1106
void cancel()
Cancel a thread.
Definition: thread.cpp:646
void cancel_finalize()
Cancel finalization.
Definition: thread.cpp:481
Mutex * loopinterrupt_antistarve_mutex
Mutex to avoid starvation when trying to lock loop_mutex.
Definition: thread.h:153
static std::string current_thread_name()
Get the name of the current thread.
Definition: thread.cpp:1318
bool cancelled() const
Check if thread has been cancelled.
Definition: thread.cpp:819
static Thread * current_thread()
Get the Thread instance of the currently running thread.
Definition: thread.cpp:1366
void notify_of_failed_init()
Notify of failed init.
Definition: thread.cpp:1218
virtual void run()
Code to execute in the thread.
Definition: thread.cpp:918
bool operator==(const Thread &thread)
Check if two threads are the same.
Definition: thread.cpp:897
void set_delete_on_exit(bool del)
Set whether the thread should be deleted on exit.
Definition: thread.cpp:1096
void remove_notification_listener(ThreadNotificationListener *notification_listener)
Remove notification listener.
Definition: thread.cpp:1171
void set_flags(uint32_t flags)
Set all flags in one go.
Definition: thread.cpp:1142
virtual void finalize()
Finalize the thread.
Definition: thread.cpp:463
OpMode
Thread operation mode.
Definition: thread.h:56
@ OPMODE_CONTINUOUS
operate in continuous mode (default)
Definition: thread.h:57
@ OPMODE_WAITFORWAKEUP
operate in wait-for-wakeup mode
Definition: thread.h:58
void set_coalesce_wakeups(bool coalesce=true)
Set wakeup coalescing.
Definition: thread.cpp:729
Wait until a given condition holds.
void wait()
Wait for the condition forever.
void wake_all()
Wake up all waiting threads.
Fawkes library namespace.