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