Fawkes API
Fawkes Development Version
|
00001 00002 /*************************************************************************** 00003 * thread.cpp - implementation of threads, based on pthreads 00004 * 00005 * Created: Thu Sep 14 13:26:39 2006 00006 * Copyright 2006-2009 Tim Niemueller [www.niemueller.de] 00007 * 00008 ****************************************************************************/ 00009 00010 /* This program is free software; you can redistribute it and/or modify 00011 * it under the terms of the GNU General Public License as published by 00012 * the Free Software Foundation; either version 2 of the License, or 00013 * (at your option) any later version. A runtime exception applies to 00014 * this software (see LICENSE.GPL_WRE file mentioned below for details). 00015 * 00016 * This program is distributed in the hope that it will be useful, 00017 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00018 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00019 * GNU Library General Public License for more details. 00020 * 00021 * Read the full text in the LICENSE.GPL_WRE file in the doc directory. 00022 */ 00023 00024 #include <core/threading/thread.h> 00025 #include <core/threading/mutex.h> 00026 #include <core/threading/mutex_locker.h> 00027 #include <core/threading/barrier.h> 00028 #include <core/threading/wait_condition.h> 00029 #include <core/threading/read_write_lock.h> 00030 #include <core/threading/thread_finalizer.h> 00031 #include <core/threading/thread_notification_listener.h> 00032 #include <core/exceptions/software.h> 00033 #include <core/exceptions/system.h> 00034 #include <core/utils/lock_list.h> 00035 00036 #include <pthread.h> 00037 #include <climits> 00038 #include <unistd.h> 00039 #include <cstring> 00040 #include <cstdlib> 00041 #include <cerrno> 00042 #include <csignal> 00043 #include <cstdio> 00044 00045 namespace fawkes { 00046 00047 /** @def forever 00048 * Shortcut for "while (1)". 00049 * @relates Thread 00050 */ 00051 00052 /** @class Thread <core/threading/thread.h> 00053 * Thread class encapsulation of pthreads. 00054 * This is the base class for all threads in Fawkes. Derive this class for 00055 * your thread. Note that you have to set a meaningful name, as this name 00056 * is necessary for easier debugging and it is used for internal messaging 00057 * via the BlackBoard. Make sure that your name is unique throughout the 00058 * software. Using the class name with an additional modifier if it is instantiated 00059 * multiple times is a good bet. 00060 * 00061 * The thread can operate in two modes. The loop can either run continuously 00062 * without a brake, or it can wait for an explicit wakeup after each loop. 00063 * Waiting for an explicit wakeup is the default since this is the common use 00064 * case in Fawkes and also it is less risky, the developer will easier see that 00065 * his thread does not do anything then fixing that the thread takes all CPU time. 00066 * 00067 * Special care has been taken to allow for proper initialization and 00068 * finalization. The special behavior of this routines can only be guaranteed 00069 * if the threads are managed properly, which is the case if we speak of the 00070 * Fawkes thread manager. This applies for the following paragraphs. 00071 * 00072 * The thread provides an init() routine which may be implemented 00073 * and is called just before the thread is started. If you make use of aspects 00074 * this is the first time when you can make use of aspects. These aspects 00075 * are not initialized in the constructor. init() is called just after the 00076 * aspect initialization. This is also the last chance to stop the thread 00077 * from being executed if you detect an error. If init() throws any exception 00078 * then the thread is never started. 00079 * 00080 * The methods prepare_finalize(), finalize() and cancel_finalize() are meant 00081 * to be used for finalization. First prepare_finalize() is called to prepare 00082 * finalization. At this stage the thread can veto and prevent finalization 00083 * from happening. For this prepare_finalize_user() has to be implemented 00084 * with the proper check, and maybe special actions that are needed to 00085 * prepare finalization (which may or may not happen independent from the 00086 * result of just this thread, see method description). Afterwards finalize() 00087 * may be called (independent of the prepare_finalize() result, see method 00088 * description). If finalize() is not executed the thread is notified with 00089 * cancel_finalize(). Before finalize() is called the thread is stopped. 00090 * 00091 * The intialization and finalization procedures may be executed deferred and 00092 * concurrent to the running thread itself. The thread is only started however 00093 * it init() finished successfully. 00094 * 00095 * The call to prepare_finalize() is mutual exclusive with a concurrently running 00096 * loop() by default. This means that if the loop() blocks waiting for some event 00097 * prepare_finalize() will hang until this event happens. This can be prevented 00098 * with set_prepfin_conc_loop() which allows to set that prepare_finalize() and 00099 * loop() may be executed concurrently. 00100 * 00101 * After prepare_finalize() has been run the thread implementation will stop the 00102 * loop() from being executed. However, the thread will still run, for example it will 00103 * wait for wakeup. This way it can be ensured that other threads will continue 00104 * to run even this thread is currently not running. An exception is the 00105 * ThreadList. For this Thread provides special synchronization features by 00106 * which it is possible to stop a thread in the very same loop iteration. That 00107 * means that if you have two threads that are woken up at the same time and 00108 * maybe even synchronize among each other it is guaranteed that both threads 00109 * will finish the running loop and never enter the next loop. 00110 * Before finalize() is called the thread shall be stopped (cancelled and joined). 00111 * 00112 * Because the finalization is done deferred and concurrent put all lengthy 00113 * finalization routines in finalize() and avoid this in the destructor, since 00114 * a long running destructor will harm the overall performance while with the 00115 * surrounding framework a long-running finalize() is acceptable. 00116 * 00117 * Please read the Fawkes documentation about guarantees (FawkesGuarantees in 00118 * the wiki) for information about the given guarantees. Several of these 00119 * guarantees are met if Thread is used in conjunction with ThreadList and the 00120 * guarantees have been specifically designed for painless plugin development. 00121 * 00122 * @ingroup Threading 00123 * @ingroup FCL 00124 * @see Aspects 00125 * @see loop() 00126 * @see run() 00127 * @see ThreadList 00128 * @see example_barrier.cpp 00129 * @see example_mutex_count.cpp 00130 * @see example_rwlock.cpp 00131 * @see example_waitcond_serialize.cpp 00132 * 00133 * @author Tim Niemueller 00134 */ 00135 00136 /** @var bool Thread::finalize_prepared 00137 * True if prepare_finalize() has been called and was not stopped with a 00138 * cancel_finalize(), false otherwise. 00139 * This can also be used in finalize() to detect whether prepare_finalize() was 00140 * run or not. 00141 */ 00142 00143 /** @var Mutex * Thread::loop_mutex 00144 * Mutex that is used to protect a call to loop(). 00145 * This mutex is locked just before loop() is called and unlocked right after it 00146 * has finished. So you can use this lock in your derivate to make sure that a 00147 * method does not run while the loop runs. 00148 * For example assume that we have a method set_parameter(int x). This method may 00149 * only be called if loop() is not running or unpredictable results will occur. 00150 * To do this you could write the method as 00151 * @code 00152 * MyThread::set_parameter(int x) 00153 * { 00154 * loopinterrupt_antistarve_mutex->lock(); 00155 * loop_mutex->lock(); 00156 * // do what you need to do... 00157 * loop_mutex->unlock(); 00158 * loopinterrupt_antistarve_mutex->unlock(); 00159 * } 00160 * @endcode 00161 * See documentation for loopinterrupt_antistarve_mutex why you need to use two 00162 * mutexes here. 00163 */ 00164 00165 /** @var Mutex * Thread::loopinterrupt_antistarve_mutex 00166 * Mutex to avoid starvation when trying to lock loop_mutex. 00167 * If you want to interrupt the main loop only locking loop_mutex is not enough, 00168 * as this might make your try to lock it starve if the loop is running too fast 00169 * (for example on a continuous thread). Because of this you always need to 00170 * lock both mutexes. The anti-starve mutex will only be visited shortly and thus 00171 * allows you to lock it easily. This will then block the thread from trying to 00172 * lock the loop_mutex. See loop_mutex for an example. 00173 */ 00174 00175 /** @fn const char * Thread::name() const 00176 * Get name of thread. 00177 * This name is mainly used for debugging purposes. Give it a descriptive 00178 * name. Is nothing is given the raw class name is used. 00179 * @return thread name 00180 */ 00181 00182 00183 /** We need not initialize this one timely by ourselves thus we do not use Mutex */ 00184 pthread_mutex_t Thread::__thread_key_mutex = PTHREAD_MUTEX_INITIALIZER; 00185 00186 00187 /** Key used to store a reference to the thread object as thread specific data. */ 00188 pthread_key_t Thread::THREAD_KEY = PTHREAD_KEYS_MAX; 00189 00190 #define MAIN_THREAD_NAME "__MainThread__" 00191 00192 /** Standard thread flag: "thread is bad" */ 00193 const unsigned int Thread::FLAG_BAD = 0x00000001; 00194 00195 /** Constructor. 00196 * This constructor is protected so that Thread cannot be instantiated. This 00197 * constructor initalizes a few internal variables. Uses continuous 00198 * operation mode. 00199 * @param name thread name, used for debugging, see Thread::name() 00200 */ 00201 Thread::Thread(const char *name) 00202 { 00203 __constructor(name, OPMODE_CONTINUOUS); 00204 } 00205 00206 00207 /** Constructor. 00208 * This constructor is protected so that Thread cannot be instantiated. This 00209 * constructor initalizes a few internal variables. 00210 * @param name thread name, used for debugging, see Thread::name() 00211 * @param op_mode Operation mode, see Thread::OpMode 00212 */ 00213 Thread::Thread(const char *name, OpMode op_mode) 00214 { 00215 __constructor(name, op_mode); 00216 } 00217 00218 00219 /** Constructor. 00220 * This constructor is protected so that Thread cannot be instantiated. This 00221 * constructor initalizes a few internal variables. 00222 * This is used to create a Thread wrapper instance for an existing thread. 00223 * Use internally only! 00224 * @param name thread name, used for debugging, see Thread::name() 00225 * @param id thread ID of running thread 00226 */ 00227 Thread::Thread(const char *name, pthread_t id) 00228 { 00229 __constructor(name, OPMODE_CONTINUOUS); 00230 __thread_id = id; 00231 } 00232 00233 00234 /** Initialize. 00235 * Kind of the base constructor. 00236 * @param name name of thread 00237 * @param op_mode operation mode 00238 */ 00239 void 00240 Thread::__constructor(const char *name, OpMode op_mode) 00241 { 00242 init_thread_key(); 00243 00244 __prepfin_conc_loop = false; 00245 __coalesce_wakeups = false; 00246 __op_mode = op_mode; 00247 __name = strdup(name); 00248 __notification_listeners = new LockList<ThreadNotificationListener *>(); 00249 00250 if ( __op_mode == OPMODE_WAITFORWAKEUP ) { 00251 __sleep_mutex = new Mutex(); 00252 __sleep_condition = new WaitCondition(__sleep_mutex); 00253 __waiting_for_wakeup = true; 00254 } else { 00255 __sleep_condition = NULL; 00256 __sleep_mutex = NULL; 00257 __waiting_for_wakeup = false; 00258 } 00259 00260 __thread_id = 0; 00261 __flags = 0; 00262 __barrier = NULL; 00263 __started = false; 00264 __cancelled = false; 00265 __delete_on_exit = false; 00266 __prepfin_hold = false; 00267 __pending_wakeups = 0; 00268 00269 loop_mutex = new Mutex(); 00270 finalize_prepared = false; 00271 00272 __loop_done = true; 00273 __loop_done_mutex = new Mutex(); 00274 __loop_done_waitcond = new WaitCondition(__loop_done_mutex); 00275 00276 loopinterrupt_antistarve_mutex = new Mutex(); 00277 __prepfin_hold_mutex = new Mutex(); 00278 __prepfin_hold_waitcond = new WaitCondition(__prepfin_hold_mutex); 00279 __startup_barrier = new Barrier(2); 00280 } 00281 00282 00283 /** Virtual destructor. */ 00284 Thread::~Thread() 00285 { 00286 __loop_done_waitcond->wake_all(); 00287 yield(); 00288 00289 delete __sleep_condition; 00290 delete __sleep_mutex; 00291 delete loop_mutex; 00292 free(__name); 00293 delete __notification_listeners; 00294 delete loopinterrupt_antistarve_mutex; 00295 delete __startup_barrier; 00296 delete __prepfin_hold_mutex; 00297 delete __prepfin_hold_waitcond; 00298 delete __loop_done_waitcond; 00299 delete __loop_done_mutex; 00300 } 00301 00302 00303 00304 /** Copy constructor is NOT supported. 00305 * Using this constructor will cause havoc and chaos. It's only here 00306 * as private constructor to hide it! Therefore if you ever use it 00307 * internally it will always throw an exception. 00308 * @param t thread to copy. 00309 * @exception Exception Always thrown 00310 */ 00311 Thread::Thread(const Thread &t) 00312 { 00313 throw Exception("You may not use copy constructor of class Thread"); 00314 } 00315 00316 00317 /** Assignment is not allowed. 00318 * You may not assign one thread to another. 00319 * @param t thread to assign 00320 */ 00321 Thread & 00322 Thread::operator=(const Thread &t) 00323 { 00324 throw Exception("You may not use assignment operator of class Thread"); 00325 } 00326 00327 00328 /** Initialize the thread. 00329 * This method is meant to be used in conjunction with aspects. Some parts 00330 * of the initialization may only happen after some aspect of the thread has 00331 * been initialized. Implement the init method with these actions. It is 00332 * guaranteed to be called just after all aspects have been initialized 00333 * and only once in the lifetime of the thread. 00334 * Throw an exception if any problem occurs and the thread should not run. 00335 * 00336 * Just because your init() routine suceeds and everything looks fine for 00337 * this thread does not automatically imply that it will run. If it belongs 00338 * to a group of threads in a ThreadList and any of the other threads fail 00339 * to initialize then no thread from this group is run and thus this thread 00340 * will never run. In that situation finalize() is called for this very 00341 * instance, prepare_finalize() however is not called. 00342 * 00343 * @see Aspects 00344 */ 00345 void 00346 Thread::init() 00347 { 00348 } 00349 00350 00351 /** Prepare finalization. 00352 * Check if finalization at this point is possible and if so execute the 00353 * steps necessary to prepare for finalization. You also have to make sure 00354 * that this state of being able to finalize does not change until either 00355 * finalize() or cancel_finalize() is called. 00356 * 00357 * This method may return false, which means that at this point the thread 00358 * cannot be stopped safely. This might be due to a critical internal 00359 * condition that may hurt hardware if turned of right now. In this case 00360 * a logger should be used to log the reason for the failure. The check is 00361 * implemented in prepare_finalize_user(), which the user has to implement 00362 * if he needs special treatment. 00363 * 00364 * Even if the finalization is said to be unsafe and false is returned, the 00365 * caller may still decide to finalize this thread, for example if all 00366 * threads are shut down on application exit. So you may not rely on the 00367 * fact that the thread is not stopped if you return false. 00368 * 00369 * You may not override this method. 00370 * 00371 * It is guaranteed that this method is only called for a running thread. 00372 * 00373 * @return true if the thread can be stopped and destroyed safely, false if 00374 * it has to stay alive 00375 * @see finalize() 00376 * @see cancel_finalize() 00377 */ 00378 bool 00379 Thread::prepare_finalize() 00380 { 00381 if ( ! __started ) { 00382 throw CannotFinalizeThreadException("Thread has not been started"); 00383 } 00384 if ( finalize_prepared ) { 00385 throw CannotFinalizeThreadException("prepare_finalize() has already been called"); 00386 } 00387 __prepfin_hold_mutex->lock(); 00388 while (__prepfin_hold) { 00389 __prepfin_hold_waitcond->wait(); 00390 } 00391 if (! __prepfin_conc_loop) { 00392 loopinterrupt_antistarve_mutex->lock(); 00393 loop_mutex->lock(); 00394 } 00395 finalize_prepared = true; 00396 bool prepared = prepare_finalize_user(); 00397 if (! __prepfin_conc_loop) { 00398 loop_mutex->unlock(); 00399 loopinterrupt_antistarve_mutex->unlock(); 00400 } 00401 __prepfin_hold_mutex->unlock(); 00402 return prepared; 00403 } 00404 00405 00406 /** Prepare finalization user implementation. 00407 * This method is called by prepare_finalize(). If there can ever be a 00408 * situation where it is not safe to turn of a thread at some point in 00409 * time then implement this method to determine these unsafe states. 00410 * 00411 * An example that comes to my mind is our Katana arm. If you turn it off 00412 * it looses all power and collapses back upon itself. This may damage the 00413 * arm if it is not in a safe position. In this situation this method would 00414 * return false to indicate this problem. 00415 * 00416 * It is up to the user to decide if this should be taken for an implied 00417 * signal to get in such a safe state, if this is possible at all. 00418 * 00419 * This feature should be used rarely as it can have tremendous implications 00420 * on the performance and experience of the whole software. In any case your 00421 * implementation should somehow inform the user of the problem that caused 00422 * the finalization to fail. If you are using aspect use the LoggerAspect and 00423 * log the reason. 00424 * 00425 * The default implementation always allows finalization. 00426 * @return true, if the thread can be finalized, false otherwise. 00427 */ 00428 bool 00429 Thread::prepare_finalize_user() 00430 { 00431 return true; 00432 } 00433 00434 00435 /** Finalize the thread. 00436 * This method is executed just before the thread is canceled and destroyed. 00437 * It is always preceeded by a call to prepare_finalize(). If this is not 00438 * the case this is a failure. The condition can be checked with 00439 * the boolean variable finalize_prepared. 00440 * 00441 * This method is meant to be used in conjunction with aspects and to cover 00442 * thread inter-dependencies. This routine MUST bring the thread into a safe 00443 * state such that it may be canceled and destroyed afterwards. If there is 00444 * any reason that this cannot happen make your prepare_finalize() reports so. 00445 * 00446 * This method is called by the thread manager just before the thread is 00447 * being cancelled. Here you can do whatever steps are necessary just before 00448 * the thread is cancelled. Note that you thread is still running and might 00449 * be in the middle of a loop, so it is not a good place to give up on all 00450 * resources used. Mind segmentation faults that could happen. Protect the 00451 * area with a mutex that you lock at the beginning of your loop and free 00452 * in the end, and that you lock at the beginning of finalize and then never 00453 * unlock. Also not that the finalization may be canceled afterwards. The 00454 * next thing that happens is that either the thread is canceled and destroyed 00455 * or that the finalization is canceled and the thread has to run again. 00456 * 00457 * Finalize is called on a thread just before it is deleted. It is guaranteed 00458 * to be called on a fully initialized thread (if no exception is thrown in 00459 * init()) (this guarantee holds in the Fawkes framework). 00460 * 00461 * The default implementation does nothing besides throwing an exception if 00462 * prepare_finalize() has not been called. 00463 * 00464 * @exception Exception thrown if prepare_finalize() has not been called. 00465 * @see prepare_finalize() 00466 * @see cancel_finalize() 00467 */ 00468 void 00469 Thread::finalize() 00470 { 00471 } 00472 00473 00474 /** Cancel finalization. 00475 * This means that something has happened (for example another thread from 00476 * the same plugin) has indicated that it can not be finalized. In that case 00477 * also this thread has to continue to run and the finalization is canceled. 00478 * The thread is expected to run after the finalization has been canceled as 00479 * if the finalization was never tried. 00480 * 00481 * This is only called on a running thread after prepare_finalization() has 00482 * been called. 00483 * 00484 * @see prepare_finalize() 00485 * @see finalize() 00486 */ 00487 void 00488 Thread::cancel_finalize() 00489 { 00490 if ( ! __started ) { 00491 throw CannotFinalizeThreadException("Cannot cancel finalize, thread has not been started"); 00492 } 00493 loop_mutex->lock(); 00494 finalize_prepared = false; 00495 loop_mutex->unlock(); 00496 } 00497 00498 00499 /** Call this method to start the thread. 00500 * This method has to be called after the thread has been instantiated and 00501 * initialized to start it. To meet the Fawkes guarantees you this may only 00502 * be called if the initialization of the thread has been successful. 00503 * @param wait if true this method will block until the thread is really 00504 * started, otherwise it will only initiate the startup and return immediately 00505 */ 00506 void 00507 Thread::start(bool wait) 00508 { 00509 int err; 00510 if (__started) { 00511 throw Exception("You cannot start the same thread twice!"); 00512 } 00513 00514 __cancelled = false; 00515 __detached = false; 00516 __started = true; 00517 __wait = wait; 00518 00519 if ( (err = pthread_create(&__thread_id, NULL, Thread::entry, this)) != 0) { 00520 // An error occured 00521 throw Exception("Could not start thread", err); 00522 } 00523 00524 if (__wait) __startup_barrier->wait(); 00525 } 00526 00527 00528 void 00529 Thread::lock_sleep_mutex() 00530 { 00531 if (__sleep_mutex) { 00532 __sleep_mutex->lock(); 00533 } 00534 } 00535 00536 00537 /** Entry point for the thread. 00538 * This is an utility method that acts as an entry point to the thread. 00539 * It is called automatically when you start the thread and will call run() 00540 * @param pthis a pointer to the instance that triggered the run of this method 00541 */ 00542 /* static */ void * 00543 Thread::entry(void *pthis) 00544 { 00545 Thread *t = (Thread *)pthis; 00546 00547 // Can be used for easier debugging in gdb, need to make this accessible 00548 // printf("Thread %s (%lu) started\n", t->name(), t->thread_id()); 00549 00550 // Set thread instance as TSD 00551 set_tsd_thread_instance(t); 00552 00553 // lock sleep mutex, needed such that thread waits for initial wakeup 00554 t->lock_sleep_mutex(); 00555 00556 // Notify listeners that this thread started 00557 t->notify_of_startup(); 00558 00559 // Thread is started now, thread that called start() will continue 00560 if (t->__wait) t->__startup_barrier->wait(); 00561 00562 // Run thread 00563 t->loop_mutex->lock(); 00564 t->once(); 00565 t->loop_mutex->unlock(); 00566 t->run(); 00567 00568 if ( t->__detached ) { 00569 // mark as stopped if detached since the thread will be deleted 00570 // after entry() is done 00571 t->__started = false; 00572 } 00573 00574 // have no useful exit value 00575 return NULL; 00576 } 00577 00578 00579 /** Exit the thread. 00580 * You may call this from within your run() method to exit the thread. 00581 * @see run() 00582 */ 00583 void 00584 Thread::exit() 00585 { 00586 if ( __delete_on_exit ) { 00587 delete this; 00588 } 00589 00590 __cancelled = true; 00591 pthread_exit(NULL); 00592 } 00593 00594 00595 /** Join the thread. 00596 * This waites for the thread to exit. 00597 */ 00598 void 00599 Thread::join() 00600 { 00601 if ( __started ) { 00602 void *dont_care; 00603 pthread_join(__thread_id, &dont_care); 00604 __started = false; 00605 00606 if ( __sleep_mutex != NULL ) { 00607 // We HAVE to release this sleep mutex under any circumstances, so we try 00608 // to lock it (locking a locked mutex or unlocking and unlocked mutex are undefined) 00609 // and then unlock it. This is for example necessary if a thread is cancelled, and 00610 // then set_opmode() is called, this would lead to a deadlock if the thread was 00611 // cancelled while waiting for the sleep lock (which is very likely) 00612 __sleep_mutex->try_lock(); 00613 __sleep_mutex->unlock(); 00614 } 00615 00616 // Force unlock of these mutexes, otherwise the same bad things as for the sleep 00617 // mutex above could happen! 00618 loop_mutex->try_lock(); 00619 loop_mutex->unlock(); 00620 } 00621 } 00622 00623 00624 /** Detach the thread. 00625 * Memory claimed by the thread will be automatically freed after the 00626 * thread exits. You can no longer join this thread. 00627 */ 00628 void 00629 Thread::detach() 00630 { 00631 __detached = true; 00632 pthread_detach(__thread_id); 00633 } 00634 00635 00636 /** Cancel a thread. 00637 * Use this to cancel the thread. 00638 */ 00639 void 00640 Thread::cancel() 00641 { 00642 if ( __started && ! __cancelled ) { 00643 if ( pthread_cancel(__thread_id) == 0 ) { 00644 __cancelled = true; 00645 } 00646 } 00647 } 00648 00649 00650 /** Send signal to a thread. 00651 * Not that sending an unhandled signal might kill the whole process, not just the 00652 * thread! 00653 * @param sig signal to send. 00654 */ 00655 void 00656 Thread::kill(int sig) 00657 { 00658 pthread_kill(__thread_id, sig); 00659 } 00660 00661 00662 /** Get operation mode. 00663 * @return opmode of thread. 00664 */ 00665 Thread::OpMode 00666 Thread::opmode() const 00667 { 00668 return __op_mode; 00669 } 00670 00671 00672 /** Set operation mode. 00673 * This can be done at any time and the thread will from the next cycle on 00674 * run in the new mode. 00675 * @param op_mode new operation mode 00676 */ 00677 void 00678 Thread::set_opmode(OpMode op_mode) 00679 { 00680 if ( __started ) { 00681 throw Exception("Cannot set thread opmode while running"); 00682 } 00683 00684 if ( (__op_mode == OPMODE_WAITFORWAKEUP) && 00685 (op_mode == OPMODE_CONTINUOUS) ) { 00686 __op_mode = OPMODE_CONTINUOUS; 00687 delete __sleep_condition; 00688 delete __sleep_mutex; 00689 __sleep_condition = NULL; 00690 __sleep_mutex = NULL; 00691 } else if ( (__op_mode == OPMODE_CONTINUOUS) && 00692 (op_mode == OPMODE_WAITFORWAKEUP) ) { 00693 __sleep_mutex = new Mutex(); 00694 __sleep_condition = new WaitCondition(__sleep_mutex); 00695 __op_mode = OPMODE_WAITFORWAKEUP; 00696 } 00697 } 00698 00699 00700 /** Set concurrent execution of prepare_finalize() and loop(). 00701 * Usually calls to prepare_finalize() and a running loop() are mutually exclusive. 00702 * The prepare_finalize() call will wait for the current loop() run to finish before 00703 * calling the user implementation. If you have a thread that blocks in its loop for 00704 * example in a blocking system call this would lead to a dead-lock if no condition 00705 * that makes the loop finish occurs. For this reason this method has been added. 00706 * If you set this to true then prepare_finalize() can be executed concurrent to 00707 * a running loop() call. If this is critical for parts of loop() you have to 00708 * protect the critical sections by yourself. Use this sparsely and be sure you really 00709 * know what you are doing. This method is necessary in some situations and powerful 00710 * if used wisely. By default a thread will enforce mutual exclusion. 00711 * @param concurrent true to allow concurrent execution of prepare_finalize() and loop(), 00712 * false to enforce mutual exclusion (the latter being the default) 00713 */ 00714 void 00715 Thread::set_prepfin_conc_loop(bool concurrent) 00716 { 00717 __prepfin_conc_loop = concurrent; 00718 } 00719 00720 00721 /** Set wakeup coalescing. 00722 * The standard behavior of multiple calls to wakeup() (before the thread actually 00723 * got woken up, for instance because a loop iteration was still running) is to 00724 * execute one iteration for each wakeup. When setting coalescing, multiple calls 00725 * will only cause a single execution of the loop. 00726 * @param coalesce true to coalesce wakeups, false to keep the original behavior 00727 */ 00728 void 00729 Thread::set_coalesce_wakeups(bool coalesce) 00730 { 00731 if ( __op_mode == OPMODE_CONTINUOUS ) { 00732 // nothing is using the value, just write it 00733 __coalesce_wakeups = coalesce; 00734 } else { 00735 // protect usage for calls to wakeup() 00736 MutexLocker lock(__sleep_mutex); 00737 __coalesce_wakeups = coalesce; 00738 } 00739 } 00740 00741 00742 /** Set name of thread. 00743 * If you want a more descriptive thread name you can do so by calling this method 00744 * in your thread's constructor, and only in the constructor. 00745 * Use parameters similar to printf(). 00746 * @param format format string 00747 */ 00748 void 00749 Thread::set_name(const char *format, ...) 00750 { 00751 va_list va; 00752 va_start(va, format); 00753 char *old_name = __name; 00754 if (vasprintf(&__name, format, va) == -1) { 00755 __name = old_name; 00756 throw OutOfMemoryException("Could not set new thread name for '%s'", __name); 00757 } else { 00758 free(old_name); 00759 } 00760 va_end(va); 00761 } 00762 00763 00764 /** Hold prepare_finalize(). 00765 * In some situations you have to hold the finalization of a thread up to a certain 00766 * safe point. With set_prepfin_hold() you can do this. If you set \p hold to true 00767 * then a call to \c prepare_finalize() will block until \c set_prepfin_hold(false) 00768 * is called. 00769 * @param hold true to hold next call to \c prepare_finalize(), false to release it 00770 * @exception Exception thrown if \c prepare_finalize() has already been called before 00771 * trying to set \p hold to true. 00772 */ 00773 void 00774 Thread::set_prepfin_hold(bool hold) 00775 { 00776 __prepfin_hold_mutex->lock(); 00777 if ( hold && finalize_prepared ) { 00778 __prepfin_hold_mutex->unlock(); 00779 throw Exception("Thread(%s)::set_prepfin_hold: prepare_finalize() has " 00780 "been called already()", __name); 00781 } 00782 __prepfin_hold = hold; 00783 if ( ! hold ) { 00784 __prepfin_hold_waitcond->wake_all(); 00785 } 00786 __prepfin_hold_mutex->unlock(); 00787 } 00788 00789 00790 /** Get ID of thread. 00791 * @return thread ID 00792 */ 00793 pthread_t 00794 Thread::thread_id() const 00795 { 00796 return __thread_id; 00797 } 00798 00799 00800 /** Check if thread has been started. 00801 * @return true if thread has been started, false otherwise 00802 */ 00803 bool 00804 Thread::started() const 00805 { 00806 return __started; 00807 } 00808 00809 00810 /** Check if thread has been cancelled. 00811 * @return true if the thread has been cancelled, false otherwise 00812 */ 00813 bool 00814 Thread::cancelled() const 00815 { 00816 return __cancelled; 00817 } 00818 00819 00820 /** Check if thread has been detached. 00821 * @return true if the thread has been detached, false otherwise 00822 */ 00823 bool 00824 Thread::detached() const 00825 { 00826 return __detached; 00827 } 00828 00829 00830 /** Check if the thread is running. 00831 * A thread is running if it currently is busy in its loop() or once() method. 00832 * @return true if the thread is running, false otherwise 00833 */ 00834 bool 00835 Thread::running() const 00836 { 00837 // loop_mutex is mutable and thus we can call the lock methods here 00838 if (loop_mutex->try_lock()) { 00839 loop_mutex->unlock(); 00840 return false; 00841 } else { 00842 return true; 00843 } 00844 } 00845 00846 00847 /** Check if thread is currently waiting for wakeup. 00848 * A continuous thread is never waiting for wakeup and thus will always return 00849 * false. A wait-for-wakeup thread is waiting when it has passed the wakeup 00850 * barrier (if supplied) and is now waiting for the next call to wakeup() 00851 * to run again. 00852 * @return true if the thread is waiting, false otherwise 00853 */ 00854 bool 00855 Thread::waiting() const 00856 { 00857 if (__op_mode != OPMODE_WAITFORWAKEUP) { 00858 return false; 00859 } else { 00860 return __waiting_for_wakeup; 00861 } 00862 } 00863 00864 /** Set cancellation point. 00865 * Tests if the thread has been canceled and if so exits the thread. 00866 */ 00867 void 00868 Thread::test_cancel() 00869 { 00870 pthread_testcancel(); 00871 } 00872 00873 00874 /** Yield the processor to another thread or process. 00875 * This will suspend the execution of the current thread in favor of other 00876 * threads. The thread will then be re-scheduled for later execution. 00877 * Use this method to make sure that other threads get a chance to get the CPU 00878 * for example if your thread is waiting for results from other threads. 00879 */ 00880 void 00881 Thread::yield() 00882 { 00883 #ifdef __USE_GNU 00884 pthread_yield(); 00885 #else 00886 usleep(0); 00887 #endif 00888 } 00889 00890 00891 /** Check if two threads are the same. 00892 * @param thread Thread to compare this thread to. 00893 * @return true, if the threads are equal, false otherwise. 00894 */ 00895 bool 00896 Thread::operator==(const Thread &thread) 00897 { 00898 return ( pthread_equal(__thread_id, thread.__thread_id) != 0 ); 00899 } 00900 00901 00902 /** Code to execute in the thread. 00903 * Executes loop() in each cycle. This is the default implementation and if 00904 * you need a more specific behaviour you can override this run() method and 00905 * ignore loop(). 00906 * Although this method is declared virtual, it should not be overridden, other 00907 * than with the following trivial snippet: 00908 * @code 00909 * protected: virtual void run() { Thread::run(); } 00910 * @endcode 00911 * The reason not to do other changes is that it contains complex house keeping 00912 * code that the system relies on. The reason for still allowing the override is 00913 * solely to make reading back traces in your debugger easier. Because now there 00914 * the class name of the thread sub-class will appear in the back trace, while 00915 * it would not otherwise. 00916 */ 00917 void 00918 Thread::run() 00919 { 00920 if ( __op_mode == OPMODE_WAITFORWAKEUP ) { 00921 // Wait for initial wakeup 00922 // __sleep_mutex has been locked in entry() already! 00923 while (__pending_wakeups == 0) { 00924 __waiting_for_wakeup = true; 00925 __sleep_condition->wait(); 00926 } 00927 __pending_wakeups -= 1; 00928 __sleep_mutex->unlock(); 00929 } 00930 00931 forever { 00932 00933 loopinterrupt_antistarve_mutex->stopby(); 00934 00935 loop_mutex->lock(); 00936 if ( ! finalize_prepared ) { 00937 __loop_done = false; 00938 loop(); 00939 } 00940 loop_mutex->unlock(); 00941 00942 __loop_done_mutex->lock(); 00943 __loop_done = true; 00944 __loop_done_mutex->unlock(); 00945 __loop_done_waitcond->wake_all(); 00946 00947 test_cancel(); 00948 if ( __op_mode == OPMODE_WAITFORWAKEUP ) { 00949 if ( __barrier ) { 00950 __sleep_mutex->lock(); 00951 Barrier *b = __barrier; 00952 __barrier = NULL; 00953 __sleep_mutex->unlock(); 00954 00955 b->wait(); 00956 00957 __sleep_mutex->lock(); 00958 } else { 00959 __sleep_mutex->lock(); 00960 } 00961 00962 while (__pending_wakeups == 0) { 00963 __waiting_for_wakeup = true; 00964 __sleep_condition->wait(); 00965 } 00966 __pending_wakeups -= 1; 00967 __sleep_mutex->unlock(); 00968 } 00969 yield(); 00970 } 00971 } 00972 00973 00974 /** Wake up thread. 00975 * If the thread is being used in wait for wakeup mode this will wake up the 00976 * waiting thread. 00977 */ 00978 void 00979 Thread::wakeup() 00980 { 00981 if ( __op_mode == OPMODE_WAITFORWAKEUP ) { 00982 MutexLocker lock(__sleep_mutex); 00983 00984 if ( __barrier ) { 00985 throw Exception("Thread(%s): wakeup() cannot be called if loop is running " 00986 "with barrier already", __name); 00987 } 00988 00989 if (__coalesce_wakeups) __pending_wakeups = 1; 00990 else __pending_wakeups += 1; 00991 if (__waiting_for_wakeup) { 00992 // currently waiting 00993 __waiting_for_wakeup = false; 00994 __sleep_condition->wake_all(); 00995 } 00996 } 00997 } 00998 00999 01000 /** Wake up thread and wait for barrier afterwards. 01001 * If the thread is being used in wait for wakeup mode this will wake up the 01002 * waiting thread. Additionally after the loop is finished 01003 * @param barrier barrier to wait for after loop 01004 */ 01005 void 01006 Thread::wakeup(Barrier *barrier) 01007 { 01008 if ( __op_mode != OPMODE_WAITFORWAKEUP ) return; 01009 01010 if ( barrier == NULL ) { 01011 throw NullPointerException("Thread(%s)::wakeup(): barrier must not be NULL", __name); 01012 } 01013 01014 MutexLocker lock(__sleep_mutex); 01015 if ( ! __waiting_for_wakeup && __barrier) { 01016 throw Exception("Thread %s already running with barrier, cannot wakeup %i %p", __name, 01017 __waiting_for_wakeup, __barrier); 01018 } 01019 01020 __pending_wakeups += 1; 01021 __barrier = barrier; 01022 if (__waiting_for_wakeup) { 01023 // currently waiting 01024 __waiting_for_wakeup = false; 01025 __sleep_condition->wake_all(); 01026 } 01027 } 01028 01029 01030 /** Wait for the current loop iteration to finish. */ 01031 void 01032 Thread::wait_loop_done() 01033 { 01034 __loop_done_mutex->lock(); 01035 while (! __loop_done) { 01036 __loop_done_waitcond->wait(); 01037 } 01038 __loop_done_mutex->unlock(); 01039 } 01040 01041 /** Code to execute in the thread. 01042 * Implement this method to hold the code you want to be executed continously. 01043 * If you do not implement this method, the default is that the thread will exit. 01044 * This is useful if you choose to only implement once(). 01045 */ 01046 void 01047 Thread::loop() 01048 { 01049 if ( __delete_on_exit ) { 01050 delete this; 01051 } 01052 pthread_exit(NULL); 01053 } 01054 01055 01056 /** Execute an action exactly once. 01057 * This code is executed once and only once right after the thread is started 01058 * before loop() is called. 01059 * This is useful if you want to implement an one-shot background job. Just implement 01060 * once() and leave once() untouched. Start the thread and detach it and it will just 01061 * do its job and then die automatically. If you use set_delete_on_exit(true) even the 01062 * Thread instance will be automatically deleted. 01063 */ 01064 void 01065 Thread::once() 01066 { 01067 } 01068 01069 01070 /** Set whether the thread should be deleted on exit. 01071 * If you set this to true the thread instance is deleted if the threads exits 01072 * (only on internal exits, not if you cancel the thread!). 01073 * This is particularly useful if you only implement once() and not loop(). 01074 * @param del true to delete thread on exit, false otherwise 01075 */ 01076 void 01077 Thread::set_delete_on_exit(bool del) 01078 { 01079 __delete_on_exit = del; 01080 } 01081 01082 01083 /** Check if wakeups are pending. 01084 * @return true if at least one more loop iteration has been queued (wakeup() has 01085 * been called), false otherwise 01086 */ 01087 bool 01088 Thread::wakeup_pending() 01089 { 01090 MutexLocker lock(__sleep_mutex); 01091 return (__pending_wakeups > 0); 01092 } 01093 01094 /** Set flag for the thread. 01095 * The first two bytes of the flags are reserved for custom usage from the outside 01096 * and they are never used internally. The last two bytes are used to indicate 01097 * internal states, like flagging a thread as bad (timing was not ok). Setting 01098 * the latter bits may have influence on the inner workings on the thread and 01099 * thus should only be done if you really know what you are doing. 01100 * @param flag flag to set 01101 * @see set_flags() 01102 */ 01103 void 01104 Thread::set_flag(uint32_t flag) 01105 { 01106 __flags |= flag; 01107 } 01108 01109 01110 /** Unset flag. 01111 * Unsets a specified flag. 01112 * @param flag flag to unset 01113 * @see set_flag() 01114 */ 01115 void 01116 Thread::unset_flag(uint32_t flag) 01117 { 01118 __flags &= 0xFFFFFFFF ^ flag; 01119 } 01120 01121 01122 /** Set all flags in one go. 01123 * @param flags flags 01124 */ 01125 void 01126 Thread::set_flags(uint32_t flags) 01127 { 01128 __flags = flags; 01129 } 01130 01131 01132 /** Check if FLAG_BAD was set. 01133 * This is a convenience method to check if FLAG_BAD has been set. 01134 * @return true if flag is set, false otherwise 01135 */ 01136 bool 01137 Thread::flagged_bad() const 01138 { 01139 return __flags & FLAG_BAD; 01140 } 01141 01142 01143 /** Add notification listener. 01144 * Add a notification listener for this thread. 01145 * @param notification_listener notification listener to add 01146 */ 01147 void 01148 Thread::add_notification_listener(ThreadNotificationListener *notification_listener) 01149 { 01150 __notification_listeners->push_back_locked(notification_listener); 01151 } 01152 01153 01154 /** Remove notification listener. 01155 * @param notification_listener notification listener to remove 01156 */ 01157 void 01158 Thread::remove_notification_listener(ThreadNotificationListener *notification_listener) 01159 { 01160 __notification_listeners->remove_locked(notification_listener); 01161 } 01162 01163 01164 /** Notify of successful startup. 01165 * This method is called internally in entry(). 01166 */ 01167 void 01168 Thread::notify_of_startup() 01169 { 01170 __notification_listeners->lock(); 01171 LockList<ThreadNotificationListener *>::iterator i = __notification_listeners->begin(); 01172 while (i != __notification_listeners->end()) { 01173 if (! (*i)->thread_started(this)) { 01174 i = __notification_listeners->erase(i); 01175 } else { 01176 ++i; 01177 } 01178 } 01179 __notification_listeners->unlock(); 01180 } 01181 01182 01183 /** Notify of failed init. 01184 * This method is called by ThreadList. 01185 */ 01186 void 01187 Thread::notify_of_failed_init() 01188 { 01189 __notification_listeners->lock(); 01190 LockList<ThreadNotificationListener *>::iterator i = __notification_listeners->begin(); 01191 while (i != __notification_listeners->end()) { 01192 if ( ! (*i)->thread_init_failed(this) ) { 01193 i = __notification_listeners->erase(i); 01194 } else { 01195 ++i; 01196 } 01197 } 01198 __notification_listeners->unlock(); 01199 } 01200 01201 01202 /** Intialize thread key. 01203 * For internal usage only. 01204 */ 01205 void 01206 Thread::init_thread_key() 01207 { 01208 pthread_mutex_lock(&__thread_key_mutex); 01209 if ( THREAD_KEY == PTHREAD_KEYS_MAX ) { 01210 // Has not been initialized, do it! 01211 int err; 01212 if ( (err = pthread_key_create(&THREAD_KEY, NULL)) != 0 ) { 01213 if ( ENOMEM == err ) { 01214 throw OutOfMemoryException("Could not create key for thread " 01215 "specific data (reference to thread)"); 01216 } else { 01217 throw Exception("Thread key for reference to thread could not be created", err); 01218 } 01219 } 01220 } 01221 pthread_mutex_unlock(&__thread_key_mutex); 01222 } 01223 01224 01225 /** Set thread instance in thread-specific data (TSD). 01226 * Use thread-specific data to store a reference to the Thread instance in the 01227 * pthread struct. Used by current_thread(). 01228 * @param t thread to set specific data on 01229 */ 01230 void 01231 Thread::set_tsd_thread_instance(Thread *t) 01232 { 01233 int err = 0; 01234 if ( (err = pthread_setspecific(THREAD_KEY, t)) != 0 ) { 01235 if ( ENOMEM == err ) { 01236 throw OutOfMemoryException("Could not set specific data (reference to thread)"); 01237 } else { 01238 throw Exception("Could not set specific data (reference to thread), unknown reason"); 01239 } 01240 } 01241 } 01242 01243 01244 /** Initialize Thread wrapper instance for main thread. 01245 * This will create an internal Thread instance such that it can be guaranteed that 01246 */ 01247 void 01248 Thread::init_main() 01249 { 01250 init_thread_key(); 01251 Thread *t = new Thread(MAIN_THREAD_NAME, pthread_self()); 01252 set_tsd_thread_instance(t); 01253 } 01254 01255 01256 /** Destroy main thread wrapper instance. 01257 * This destroys the thread wrapper created with init_main(). Note that 01258 * this has to be called from the very same thread that init_main() was called 01259 * from, which should be the main thread (somewhere from main() on). 01260 */ 01261 void 01262 Thread::destroy_main() 01263 { 01264 Thread *t = current_thread(); 01265 if ( strcmp(t->name(), MAIN_THREAD_NAME) == 0 ) { 01266 delete t; 01267 } else { 01268 throw Exception("Main thread can only be destroyed in main thread"); 01269 } 01270 } 01271 01272 01273 /** Get the ID of the currently running thread. 01274 * This will return the ID of the thread in which's context this method was 01275 * called. 01276 * @return ID of thread context 01277 */ 01278 pthread_t 01279 Thread::current_thread_id() 01280 { 01281 return pthread_self(); 01282 } 01283 01284 01285 /** Get the Thread instance of the currently running thread. 01286 * This will return the Thread instance of the thread in which's context this method was 01287 * called. 01288 * Note that only if the main application ensures to call init_main() it can be guaranteed 01289 * that this value is not NULL. 01290 * @return Thread instance of the current thread 01291 * @exception Exception thrown if this method is called before either init_main() is 01292 * called or any one thread has been started. 01293 */ 01294 Thread * 01295 Thread::current_thread() 01296 { 01297 if ( THREAD_KEY == PTHREAD_KEYS_MAX ) { 01298 throw Exception("No thread has been initialized"); 01299 } 01300 return (Thread *)pthread_getspecific(THREAD_KEY); 01301 } 01302 01303 01304 /** Similar to current_thread, but does never throw an exception. 01305 * This is a convenience method doing the same as current_thread(), but it never ever 01306 * throws an exception, rather it returns NULL in case of an error. This is necessary 01307 * if run from a C context. 01308 * @return Thread instance of the current thread 01309 */ 01310 Thread * 01311 Thread::current_thread_noexc() throw() 01312 { 01313 if ( THREAD_KEY == PTHREAD_KEYS_MAX ) { 01314 return 0; 01315 } 01316 return (Thread *)pthread_getspecific(THREAD_KEY); 01317 } 01318 01319 01320 /** Set the cancel state of the current thread. 01321 * The cancel state can only be set on the current thread. Please also 01322 * consider the documentation for pthread_setcancelstate(). 01323 * @param new_state new cancel state 01324 * @param old_state old cancel state 01325 */ 01326 void 01327 Thread::set_cancel_state(CancelState new_state, CancelState *old_state) 01328 { 01329 int oldstate = PTHREAD_CANCEL_ENABLE; 01330 int newstate = PTHREAD_CANCEL_ENABLE; 01331 if ( new_state == CANCEL_DISABLED ) { 01332 newstate = PTHREAD_CANCEL_DISABLE; 01333 } 01334 01335 pthread_setcancelstate(newstate, &oldstate); 01336 01337 if ( old_state != NULL ) { 01338 if ( oldstate == PTHREAD_CANCEL_DISABLE ) { 01339 *old_state = CANCEL_DISABLED; 01340 } else { 01341 *old_state = CANCEL_ENABLED; 01342 } 01343 } 01344 } 01345 01346 01347 } // end namespace fawkes