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 loopinterrupt_antistarve_mutex = new Mutex(); 00273 __prepfin_hold_mutex = new Mutex(); 00274 __prepfin_hold_waitcond = new WaitCondition(__prepfin_hold_mutex); 00275 __startup_barrier = new Barrier(2); 00276 } 00277 00278 00279 /** Virtual destructor. */ 00280 Thread::~Thread() 00281 { 00282 delete __sleep_condition; 00283 delete __sleep_mutex; 00284 delete loop_mutex; 00285 free(__name); 00286 delete __notification_listeners; 00287 delete loopinterrupt_antistarve_mutex; 00288 delete __startup_barrier; 00289 delete __prepfin_hold_mutex; 00290 delete __prepfin_hold_waitcond; 00291 } 00292 00293 00294 00295 /** Copy constructor is NOT supported. 00296 * Using this constructor will cause havoc and chaos. It's only here 00297 * as private constructor to hide it! Therefore if you ever use it 00298 * internally it will always throw an exception. 00299 * @param t thread to copy. 00300 * @exception Exception Always thrown 00301 */ 00302 Thread::Thread(const Thread &t) 00303 { 00304 throw Exception("You may not use copy constructor of class Thread"); 00305 } 00306 00307 00308 /** Assignment is not allowed. 00309 * You may not assign one thread to another. 00310 * @param t thread to assign 00311 */ 00312 Thread & 00313 Thread::operator=(const Thread &t) 00314 { 00315 throw Exception("You may not use assignment operator of class Thread"); 00316 } 00317 00318 00319 /** Initialize the thread. 00320 * This method is meant to be used in conjunction with aspects. Some parts 00321 * of the initialization may only happen after some aspect of the thread has 00322 * been initialized. Implement the init method with these actions. It is 00323 * guaranteed to be called just after all aspects have been initialized 00324 * and only once in the lifetime of the thread. 00325 * Throw an exception if any problem occurs and the thread should not run. 00326 * 00327 * Just because your init() routine suceeds and everything looks fine for 00328 * this thread does not automatically imply that it will run. If it belongs 00329 * to a group of threads in a ThreadList and any of the other threads fail 00330 * to initialize then no thread from this group is run and thus this thread 00331 * will never run. In that situation finalize() is called for this very 00332 * instance, prepare_finalize() however is not called. 00333 * 00334 * @see Aspects 00335 */ 00336 void 00337 Thread::init() 00338 { 00339 } 00340 00341 00342 /** Prepare finalization. 00343 * Check if finalization at this point is possible and if so execute the 00344 * steps necessary to prepare for finalization. You also have to make sure 00345 * that this state of being able to finalize does not change until either 00346 * finalize() or cancel_finalize() is called. 00347 * 00348 * This method may return false, which means that at this point the thread 00349 * cannot be stopped safely. This might be due to a critical internal 00350 * condition that may hurt hardware if turned of right now. In this case 00351 * a logger should be used to log the reason for the failure. The check is 00352 * implemented in prepare_finalize_user(), which the user has to implement 00353 * if he needs special treatment. 00354 * 00355 * Even if the finalization is said to be unsafe and false is returned, the 00356 * caller may still decide to finalize this thread, for example if all 00357 * threads are shut down on application exit. So you may not rely on the 00358 * fact that the thread is not stopped if you return false. 00359 * 00360 * You may not override this method. 00361 * 00362 * It is guaranteed that this method is only called for a running thread. 00363 * 00364 * @return true if the thread can be stopped and destroyed safely, false if 00365 * it has to stay alive 00366 * @see finalize() 00367 * @see cancel_finalize() 00368 */ 00369 bool 00370 Thread::prepare_finalize() 00371 { 00372 if ( ! __started ) { 00373 throw CannotFinalizeThreadException("Thread has not been started"); 00374 } 00375 if ( finalize_prepared ) { 00376 throw CannotFinalizeThreadException("prepare_finalize() has already been called"); 00377 } 00378 __prepfin_hold_mutex->lock(); 00379 while (__prepfin_hold) { 00380 __prepfin_hold_waitcond->wait(); 00381 } 00382 if (! __prepfin_conc_loop) { 00383 loopinterrupt_antistarve_mutex->lock(); 00384 loop_mutex->lock(); 00385 } 00386 finalize_prepared = true; 00387 bool prepared = prepare_finalize_user(); 00388 if (! __prepfin_conc_loop) { 00389 loop_mutex->unlock(); 00390 loopinterrupt_antistarve_mutex->unlock(); 00391 } 00392 __prepfin_hold_mutex->unlock(); 00393 return prepared; 00394 } 00395 00396 00397 /** Prepare finalization user implementation. 00398 * This method is called by prepare_finalize(). If there can ever be a 00399 * situation where it is not safe to turn of a thread at some point in 00400 * time then implement this method to determine these unsafe states. 00401 * 00402 * An example that comes to my mind is our Katana arm. If you turn it off 00403 * it looses all power and collapses back upon itself. This may damage the 00404 * arm if it is not in a safe position. In this situation this method would 00405 * return false to indicate this problem. 00406 * 00407 * It is up to the user to decide if this should be taken for an implied 00408 * signal to get in such a safe state, if this is possible at all. 00409 * 00410 * This feature should be used rarely as it can have tremendous implications 00411 * on the performance and experience of the whole software. In any case your 00412 * implementation should somehow inform the user of the problem that caused 00413 * the finalization to fail. If you are using aspect use the LoggerAspect and 00414 * log the reason. 00415 * 00416 * The default implementation always allows finalization. 00417 * @return true, if the thread can be finalized, false otherwise. 00418 */ 00419 bool 00420 Thread::prepare_finalize_user() 00421 { 00422 return true; 00423 } 00424 00425 00426 /** Finalize the thread. 00427 * This method is executed just before the thread is canceled and destroyed. 00428 * It is always preceeded by a call to prepare_finalize(). If this is not 00429 * the case this is a failure. The condition can be checked with 00430 * the boolean variable finalize_prepared. 00431 * 00432 * This method is meant to be used in conjunction with aspects and to cover 00433 * thread inter-dependencies. This routine MUST bring the thread into a safe 00434 * state such that it may be canceled and destroyed afterwards. If there is 00435 * any reason that this cannot happen make your prepare_finalize() reports so. 00436 * 00437 * This method is called by the thread manager just before the thread is 00438 * being cancelled. Here you can do whatever steps are necessary just before 00439 * the thread is cancelled. Note that you thread is still running and might 00440 * be in the middle of a loop, so it is not a good place to give up on all 00441 * resources used. Mind segmentation faults that could happen. Protect the 00442 * area with a mutex that you lock at the beginning of your loop and free 00443 * in the end, and that you lock at the beginning of finalize and then never 00444 * unlock. Also not that the finalization may be canceled afterwards. The 00445 * next thing that happens is that either the thread is canceled and destroyed 00446 * or that the finalization is canceled and the thread has to run again. 00447 * 00448 * Finalize is called on a thread just before it is deleted. It is guaranteed 00449 * to be called on a fully initialized thread (if no exception is thrown in 00450 * init()) (this guarantee holds in the Fawkes framework). 00451 * 00452 * The default implementation does nothing besides throwing an exception if 00453 * prepare_finalize() has not been called. 00454 * 00455 * @exception Exception thrown if prepare_finalize() has not been called. 00456 * @see prepare_finalize() 00457 * @see cancel_finalize() 00458 */ 00459 void 00460 Thread::finalize() 00461 { 00462 } 00463 00464 00465 /** Cancel finalization. 00466 * This means that something has happened (for example another thread from 00467 * the same plugin) has indicated that it can not be finalized. In that case 00468 * also this thread has to continue to run and the finalization is canceled. 00469 * The thread is expected to run after the finalization has been canceled as 00470 * if the finalization was never tried. 00471 * 00472 * This is only called on a running thread after prepare_finalization() has 00473 * been called. 00474 * 00475 * @see prepare_finalize() 00476 * @see finalize() 00477 */ 00478 void 00479 Thread::cancel_finalize() 00480 { 00481 if ( ! __started ) { 00482 throw CannotFinalizeThreadException("Cannot cancel finalize, thread has not been started"); 00483 } 00484 loop_mutex->lock(); 00485 finalize_prepared = false; 00486 loop_mutex->unlock(); 00487 } 00488 00489 00490 /** Call this method to start the thread. 00491 * This method has to be called after the thread has been instantiated and 00492 * initialized to start it. To meet the Fawkes guarantees you this may only 00493 * be called if the initialization of the thread has been successful. 00494 * @param wait if true this method will block until the thread is really 00495 * started, otherwise it will only initiate the startup and return immediately 00496 */ 00497 void 00498 Thread::start(bool wait) 00499 { 00500 int err; 00501 if (__started) { 00502 throw Exception("You cannot start the same thread twice!"); 00503 } 00504 00505 __cancelled = false; 00506 __detached = false; 00507 __started = true; 00508 __wait = wait; 00509 00510 if ( (err = pthread_create(&__thread_id, NULL, Thread::entry, this)) != 0) { 00511 // An error occured 00512 throw Exception("Could not start thread", err); 00513 } 00514 00515 if (__wait) __startup_barrier->wait(); 00516 } 00517 00518 00519 void 00520 Thread::lock_sleep_mutex() 00521 { 00522 if (__sleep_mutex) { 00523 __sleep_mutex->lock(); 00524 } 00525 } 00526 00527 00528 /** Entry point for the thread. 00529 * This is an utility method that acts as an entry point to the thread. 00530 * It is called automatically when you start the thread and will call run() 00531 * @param pthis a pointer to the instance that triggered the run of this method 00532 */ 00533 /* static */ void * 00534 Thread::entry(void *pthis) 00535 { 00536 Thread *t = (Thread *)pthis; 00537 00538 // Can be used for easier debugging in gdb, need to make this accessible 00539 // printf("Thread %s (%lu) started\n", t->name(), t->thread_id()); 00540 00541 // Set thread instance as TSD 00542 set_tsd_thread_instance(t); 00543 00544 // lock sleep mutex, needed such that thread waits for initial wakeup 00545 t->lock_sleep_mutex(); 00546 00547 // Notify listeners that this thread started 00548 t->notify_of_startup(); 00549 00550 // Thread is started now, thread that called start() will continue 00551 if (t->__wait) t->__startup_barrier->wait(); 00552 00553 // Run thread 00554 t->loop_mutex->lock(); 00555 t->once(); 00556 t->loop_mutex->unlock(); 00557 t->run(); 00558 00559 if ( t->__detached ) { 00560 // mark as stopped if detached since the thread will be deleted 00561 // after entry() is done 00562 t->__started = false; 00563 } 00564 00565 // have no useful exit value 00566 return NULL; 00567 } 00568 00569 00570 /** Exit the thread. 00571 * You may call this from within your run() method to exit the thread. 00572 * @see run() 00573 */ 00574 void 00575 Thread::exit() 00576 { 00577 if ( __delete_on_exit ) { 00578 delete this; 00579 } 00580 00581 __cancelled = true; 00582 pthread_exit(NULL); 00583 } 00584 00585 00586 /** Join the thread. 00587 * This waites for the thread to exit. 00588 */ 00589 void 00590 Thread::join() 00591 { 00592 if ( __started ) { 00593 void *dont_care; 00594 pthread_join(__thread_id, &dont_care); 00595 __started = false; 00596 00597 if ( __sleep_mutex != NULL ) { 00598 // We HAVE to release this sleep mutex under any circumstances, so we try 00599 // to lock it (locking a locked mutex or unlocking and unlocked mutex are undefined) 00600 // and then unlock it. This is for example necessary if a thread is cancelled, and 00601 // then set_opmode() is called, this would lead to a deadlock if the thread was 00602 // cancelled while waiting for the sleep lock (which is very likely) 00603 __sleep_mutex->try_lock(); 00604 __sleep_mutex->unlock(); 00605 } 00606 00607 // Force unlock of these mutexes, otherwise the same bad things as for the sleep 00608 // mutex above could happen! 00609 loop_mutex->try_lock(); 00610 loop_mutex->unlock(); 00611 } 00612 } 00613 00614 00615 /** Detach the thread. 00616 * Memory claimed by the thread will be automatically freed after the 00617 * thread exits. You can no longer join this thread. 00618 */ 00619 void 00620 Thread::detach() 00621 { 00622 __detached = true; 00623 pthread_detach(__thread_id); 00624 } 00625 00626 00627 /** Cancel a thread. 00628 * Use this to cancel the thread. 00629 */ 00630 void 00631 Thread::cancel() 00632 { 00633 if ( __started && ! __cancelled ) { 00634 if ( pthread_cancel(__thread_id) == 0 ) { 00635 __cancelled = true; 00636 } 00637 } 00638 } 00639 00640 00641 /** Send signal to a thread. 00642 * Not that sending an unhandled signal might kill the whole process, not just the 00643 * thread! 00644 * @param sig signal to send. 00645 */ 00646 void 00647 Thread::kill(int sig) 00648 { 00649 pthread_kill(__thread_id, sig); 00650 } 00651 00652 00653 /** Get operation mode. 00654 * @return opmode of thread. 00655 */ 00656 Thread::OpMode 00657 Thread::opmode() const 00658 { 00659 return __op_mode; 00660 } 00661 00662 00663 /** Set operation mode. 00664 * This can be done at any time and the thread will from the next cycle on 00665 * run in the new mode. 00666 * @param op_mode new operation mode 00667 */ 00668 void 00669 Thread::set_opmode(OpMode op_mode) 00670 { 00671 if ( __started ) { 00672 throw Exception("Cannot set thread opmode while running"); 00673 } 00674 00675 if ( (__op_mode == OPMODE_WAITFORWAKEUP) && 00676 (op_mode == OPMODE_CONTINUOUS) ) { 00677 __op_mode = OPMODE_CONTINUOUS; 00678 delete __sleep_condition; 00679 delete __sleep_mutex; 00680 __sleep_condition = NULL; 00681 __sleep_mutex = NULL; 00682 } else if ( (__op_mode == OPMODE_CONTINUOUS) && 00683 (op_mode == OPMODE_WAITFORWAKEUP) ) { 00684 __sleep_mutex = new Mutex(); 00685 __sleep_condition = new WaitCondition(__sleep_mutex); 00686 __op_mode = OPMODE_WAITFORWAKEUP; 00687 } 00688 } 00689 00690 00691 /** Set concurrent execution of prepare_finalize() and loop(). 00692 * Usually calls to prepare_finalize() and a running loop() are mutually exclusive. 00693 * The prepare_finalize() call will wait for the current loop() run to finish before 00694 * calling the user implementation. If you have a thread that blocks in its loop for 00695 * example in a blocking system call this would lead to a dead-lock if no condition 00696 * that makes the loop finish occurs. For this reason this method has been added. 00697 * If you set this to true then prepare_finalize() can be executed concurrent to 00698 * a running loop() call. If this is critical for parts of loop() you have to 00699 * protect the critical sections by yourself. Use this sparsely and be sure you really 00700 * know what you are doing. This method is necessary in some situations and powerful 00701 * if used wisely. By default a thread will enforce mutual exclusion. 00702 * @param concurrent true to allow concurrent execution of prepare_finalize() and loop(), 00703 * false to enforce mutual exclusion (the latter being the default) 00704 */ 00705 void 00706 Thread::set_prepfin_conc_loop(bool concurrent) 00707 { 00708 __prepfin_conc_loop = concurrent; 00709 } 00710 00711 00712 /** Set wakeup coalescing. 00713 * The standard behavior of multiple calls to wakeup() (before the thread actually 00714 * got woken up, for instance because a loop iteration was still running) is to 00715 * execute one iteration for each wakeup. When setting coalescing, multiple calls 00716 * will only cause a single execution of the loop. 00717 * @param coalesce true to coalesce wakeups, false to keep the original behavior 00718 */ 00719 void 00720 Thread::set_coalesce_wakeups(bool coalesce) 00721 { 00722 if ( __op_mode == OPMODE_CONTINUOUS ) { 00723 // nothing is using the value, just write it 00724 __coalesce_wakeups = coalesce; 00725 } else { 00726 // protect usage for calls to wakeup() 00727 MutexLocker lock(__sleep_mutex); 00728 __coalesce_wakeups = coalesce; 00729 } 00730 } 00731 00732 00733 /** Set name of thread. 00734 * If you want a more descriptive thread name you can do so by calling this method 00735 * in your thread's constructor, and only in the constructor. 00736 * Use parameters similar to printf(). 00737 * @param format format string 00738 */ 00739 void 00740 Thread::set_name(const char *format, ...) 00741 { 00742 va_list va; 00743 va_start(va, format); 00744 char *old_name = __name; 00745 if (vasprintf(&__name, format, va) == -1) { 00746 __name = old_name; 00747 throw OutOfMemoryException("Could not set new thread name for '%s'", __name); 00748 } else { 00749 free(old_name); 00750 } 00751 va_end(va); 00752 } 00753 00754 00755 /** Hold prepare_finalize(). 00756 * In some situations you have to hold the finalization of a thread up to a certain 00757 * safe point. With set_prepfin_hold() you can do this. If you set \p hold to true 00758 * then a call to \c prepare_finalize() will block until \c set_prepfin_hold(false) 00759 * is called. 00760 * @param hold true to hold next call to \c prepare_finalize(), false to release it 00761 * @exception Exception thrown if \c prepare_finalize() has already been called before 00762 * trying to set \p hold to true. 00763 */ 00764 void 00765 Thread::set_prepfin_hold(bool hold) 00766 { 00767 __prepfin_hold_mutex->lock(); 00768 if ( hold && finalize_prepared ) { 00769 __prepfin_hold_mutex->unlock(); 00770 throw Exception("Thread(%s)::set_prepfin_hold: prepare_finalize() has " 00771 "been called already()", __name); 00772 } 00773 __prepfin_hold = hold; 00774 if ( ! hold ) { 00775 __prepfin_hold_waitcond->wake_all(); 00776 } 00777 __prepfin_hold_mutex->unlock(); 00778 } 00779 00780 00781 /** Get ID of thread. 00782 * @return thread ID 00783 */ 00784 pthread_t 00785 Thread::thread_id() const 00786 { 00787 return __thread_id; 00788 } 00789 00790 00791 /** Check if thread has been started. 00792 * @return true if thread has been started, false otherwise 00793 */ 00794 bool 00795 Thread::started() const 00796 { 00797 return __started; 00798 } 00799 00800 00801 /** Check if thread has been cancelled. 00802 * @return true if the thread has been cancelled, false otherwise 00803 */ 00804 bool 00805 Thread::cancelled() const 00806 { 00807 return __cancelled; 00808 } 00809 00810 00811 /** Check if thread has been detached. 00812 * @return true if the thread has been detached, false otherwise 00813 */ 00814 bool 00815 Thread::detached() const 00816 { 00817 return __detached; 00818 } 00819 00820 00821 /** Check if the thread is running. 00822 * A thread is running if it currently is busy in its loop() or once() method. 00823 * @return true if the thread is running, false otherwise 00824 */ 00825 bool 00826 Thread::running() const 00827 { 00828 // loop_mutex is mutable and thus we can call the lock methods here 00829 if (loop_mutex->try_lock()) { 00830 loop_mutex->unlock(); 00831 return false; 00832 } else { 00833 return true; 00834 } 00835 } 00836 00837 00838 /** Check if thread is currently waiting for wakeup. 00839 * A continuous thread is never waiting for wakeup and thus will always return 00840 * false. A wait-for-wakeup thread is waiting when it has passed the wakeup 00841 * barrier (if supplied) and is now waiting for the next call to wakeup() 00842 * to run again. 00843 * @return true if the thread is waiting, false otherwise 00844 */ 00845 bool 00846 Thread::waiting() const 00847 { 00848 if (__op_mode != OPMODE_WAITFORWAKEUP) { 00849 return false; 00850 } else { 00851 return __waiting_for_wakeup; 00852 } 00853 } 00854 00855 /** Set cancellation point. 00856 * Tests if the thread has been canceled and if so exits the thread. 00857 */ 00858 void 00859 Thread::test_cancel() 00860 { 00861 pthread_testcancel(); 00862 } 00863 00864 00865 /** Yield the processor to another thread or process. 00866 * This will suspend the execution of the current thread in favor of other 00867 * threads. The thread will then be re-scheduled for later execution. 00868 * Use this method to make sure that other threads get a chance to get the CPU 00869 * for example if your thread is waiting for results from other threads. 00870 */ 00871 void 00872 Thread::yield() 00873 { 00874 #ifdef __USE_GNU 00875 pthread_yield(); 00876 #else 00877 usleep(0); 00878 #endif 00879 } 00880 00881 00882 /** Check if two threads are the same. 00883 * @param thread Thread to compare this thread to. 00884 * @return true, if the threads are equal, false otherwise. 00885 */ 00886 bool 00887 Thread::operator==(const Thread &thread) 00888 { 00889 return ( pthread_equal(__thread_id, thread.__thread_id) != 0 ); 00890 } 00891 00892 00893 /** Code to execute in the thread. 00894 * Executes loop() in each cycle. This is the default implementation and if 00895 * you need a more specific behaviour you can override this run() method and 00896 * ignore loop(). 00897 * Although this method is declared virtual, it should not be overridden, other 00898 * than with the following trivial snippet: 00899 * @code 00900 * protected: virtual void run() { Thread::run(); } 00901 * @endcode 00902 * The reason not to do other changes is that it contains complex house keeping 00903 * code that the system relies on. The reason for still allowing the override is 00904 * solely to make reading back traces in your debugger easier. Because now there 00905 * the class name of the thread sub-class will appear in the back trace, while 00906 * it would not otherwise. 00907 */ 00908 void 00909 Thread::run() 00910 { 00911 if ( __op_mode == OPMODE_WAITFORWAKEUP ) { 00912 // Wait for initial wakeup 00913 // __sleep_mutex has been locked in entry() already! 00914 while (__pending_wakeups == 0) { 00915 __waiting_for_wakeup = true; 00916 __sleep_condition->wait(); 00917 } 00918 __pending_wakeups -= 1; 00919 __sleep_mutex->unlock(); 00920 } 00921 00922 forever { 00923 00924 loopinterrupt_antistarve_mutex->stopby(); 00925 00926 loop_mutex->lock(); 00927 if ( ! finalize_prepared ) { 00928 loop(); 00929 } 00930 loop_mutex->unlock(); 00931 00932 test_cancel(); 00933 if ( __op_mode == OPMODE_WAITFORWAKEUP ) { 00934 if ( __barrier ) { 00935 __barrier->wait(); 00936 __sleep_mutex->lock(); 00937 if (__pending_wakeups == 0) __barrier = NULL; 00938 } else { 00939 __sleep_mutex->lock(); 00940 } 00941 00942 while (__pending_wakeups == 0) { 00943 __waiting_for_wakeup = true; 00944 __sleep_condition->wait(); 00945 } 00946 __pending_wakeups -= 1; 00947 __sleep_mutex->unlock(); 00948 } 00949 yield(); 00950 } 00951 } 00952 00953 00954 /** Wake up thread. 00955 * If the thread is being used in wait for wakeup mode this will wake up the 00956 * waiting thread. 00957 */ 00958 void 00959 Thread::wakeup() 00960 { 00961 if ( __op_mode == OPMODE_WAITFORWAKEUP ) { 00962 MutexLocker lock(__sleep_mutex); 00963 00964 if ( __barrier ) { 00965 throw Exception("Thread(%s): wakeup() cannot be called if loop is running " 00966 "with barrier already", __name); 00967 } 00968 00969 if (__coalesce_wakeups) __pending_wakeups = 1; 00970 else __pending_wakeups += 1; 00971 if (__waiting_for_wakeup) { 00972 // currently waiting 00973 __waiting_for_wakeup = false; 00974 __sleep_condition->wake_all(); 00975 } 00976 } 00977 } 00978 00979 00980 /** Wake up thread and wait for barrier afterwards. 00981 * If the thread is being used in wait for wakeup mode this will wake up the 00982 * waiting thread. Additionally after the loop is finished 00983 * @param barrier barrier to wait for after loop 00984 */ 00985 void 00986 Thread::wakeup(Barrier *barrier) 00987 { 00988 if ( __op_mode != OPMODE_WAITFORWAKEUP ) return; 00989 00990 if ( barrier == NULL ) { 00991 throw NullPointerException("Thread(%s)::wakeup(): barrier must not be NULL", __name); 00992 } 00993 00994 MutexLocker lock(__sleep_mutex); 00995 if ( ! __waiting_for_wakeup && __barrier && (__barrier != barrier)) { 00996 throw Exception("Thread %s already running with other barrier, cannot wakeup", __name); 00997 } 00998 00999 __pending_wakeups += 1; 01000 __barrier = barrier; 01001 if (__waiting_for_wakeup) { 01002 // currently waiting 01003 __waiting_for_wakeup = false; 01004 __sleep_condition->wake_all(); 01005 } 01006 } 01007 01008 01009 /** Code to execute in the thread. 01010 * Implement this method to hold the code you want to be executed continously. 01011 * If you do not implement this method, the default is that the thread will exit. 01012 * This is useful if you choose to only implement once(). 01013 */ 01014 void 01015 Thread::loop() 01016 { 01017 if ( __delete_on_exit ) { 01018 delete this; 01019 } 01020 pthread_exit(NULL); 01021 } 01022 01023 01024 /** Execute an action exactly once. 01025 * This code is executed once and only once right after the thread is started 01026 * before loop() is called. 01027 * This is useful if you want to implement an one-shot background job. Just implement 01028 * once() and leave once() untouched. Start the thread and detach it and it will just 01029 * do its job and then die automatically. If you use set_delete_on_exit(true) even the 01030 * Thread instance will be automatically deleted. 01031 */ 01032 void 01033 Thread::once() 01034 { 01035 } 01036 01037 01038 /** Set whether the thread should be deleted on exit. 01039 * If you set this to true the thread instance is deleted if the threads exits 01040 * (only on internal exits, not if you cancel the thread!). 01041 * This is particularly useful if you only implement once() and not loop(). 01042 * @param del true to delete thread on exit, false otherwise 01043 */ 01044 void 01045 Thread::set_delete_on_exit(bool del) 01046 { 01047 __delete_on_exit = del; 01048 } 01049 01050 01051 /** Check if wakeups are pending. 01052 * @return true if at least one more loop iteration has been queued (wakeup() has 01053 * been called), false otherwise 01054 */ 01055 bool 01056 Thread::wakeup_pending() 01057 { 01058 MutexLocker lock(__sleep_mutex); 01059 return (__pending_wakeups > 0); 01060 } 01061 01062 /** Set flag for the thread. 01063 * The first two bytes of the flags are reserved for custom usage from the outside 01064 * and they are never used internally. The last two bytes are used to indicate 01065 * internal states, like flagging a thread as bad (timing was not ok). Setting 01066 * the latter bits may have influence on the inner workings on the thread and 01067 * thus should only be done if you really know what you are doing. 01068 * @param flag flag to set 01069 * @see set_flags() 01070 */ 01071 void 01072 Thread::set_flag(uint32_t flag) 01073 { 01074 __flags |= flag; 01075 } 01076 01077 01078 /** Unset flag. 01079 * Unsets a specified flag. 01080 * @param flag flag to unset 01081 * @see set_flag() 01082 */ 01083 void 01084 Thread::unset_flag(uint32_t flag) 01085 { 01086 __flags &= 0xFFFFFFFF ^ flag; 01087 } 01088 01089 01090 /** Set all flags in one go. 01091 * @param flags flags 01092 */ 01093 void 01094 Thread::set_flags(uint32_t flags) 01095 { 01096 __flags = flags; 01097 } 01098 01099 01100 /** Check if FLAG_BAD was set. 01101 * This is a convenience method to check if FLAG_BAD has been set. 01102 * @return true if flag is set, false otherwise 01103 */ 01104 bool 01105 Thread::flagged_bad() const 01106 { 01107 return __flags & FLAG_BAD; 01108 } 01109 01110 01111 /** Add notification listener. 01112 * Add a notification listener for this thread. 01113 * @param notification_listener notification listener to add 01114 */ 01115 void 01116 Thread::add_notification_listener(ThreadNotificationListener *notification_listener) 01117 { 01118 __notification_listeners->push_back_locked(notification_listener); 01119 } 01120 01121 01122 /** Remove notification listener. 01123 * @param notification_listener notification listener to remove 01124 */ 01125 void 01126 Thread::remove_notification_listener(ThreadNotificationListener *notification_listener) 01127 { 01128 __notification_listeners->remove_locked(notification_listener); 01129 } 01130 01131 01132 /** Notify of successful startup. 01133 * This method is called internally in entry(). 01134 */ 01135 void 01136 Thread::notify_of_startup() 01137 { 01138 __notification_listeners->lock(); 01139 LockList<ThreadNotificationListener *>::iterator i = __notification_listeners->begin(); 01140 while (i != __notification_listeners->end()) { 01141 if (! (*i)->thread_started(this)) { 01142 i = __notification_listeners->erase(i); 01143 } else { 01144 ++i; 01145 } 01146 } 01147 __notification_listeners->unlock(); 01148 } 01149 01150 01151 /** Notify of failed init. 01152 * This method is called by ThreadList. 01153 */ 01154 void 01155 Thread::notify_of_failed_init() 01156 { 01157 __notification_listeners->lock(); 01158 LockList<ThreadNotificationListener *>::iterator i = __notification_listeners->begin(); 01159 while (i != __notification_listeners->end()) { 01160 if ( ! (*i)->thread_init_failed(this) ) { 01161 i = __notification_listeners->erase(i); 01162 } else { 01163 ++i; 01164 } 01165 } 01166 __notification_listeners->unlock(); 01167 } 01168 01169 01170 /** Intialize thread key. 01171 * For internal usage only. 01172 */ 01173 void 01174 Thread::init_thread_key() 01175 { 01176 pthread_mutex_lock(&__thread_key_mutex); 01177 if ( THREAD_KEY == PTHREAD_KEYS_MAX ) { 01178 // Has not been initialized, do it! 01179 int err; 01180 if ( (err = pthread_key_create(&THREAD_KEY, NULL)) != 0 ) { 01181 if ( ENOMEM == err ) { 01182 throw OutOfMemoryException("Could not create key for thread " 01183 "specific data (reference to thread)"); 01184 } else { 01185 throw Exception("Thread key for reference to thread could not be created", err); 01186 } 01187 } 01188 } 01189 pthread_mutex_unlock(&__thread_key_mutex); 01190 } 01191 01192 01193 /** Set thread instance in thread-specific data (TSD). 01194 * Use thread-specific data to store a reference to the Thread instance in the 01195 * pthread struct. Used by current_thread(). 01196 * @param t thread to set specific data on 01197 */ 01198 void 01199 Thread::set_tsd_thread_instance(Thread *t) 01200 { 01201 int err = 0; 01202 if ( (err = pthread_setspecific(THREAD_KEY, t)) != 0 ) { 01203 if ( ENOMEM == err ) { 01204 throw OutOfMemoryException("Could not set specific data (reference to thread)"); 01205 } else { 01206 throw Exception("Could not set specific data (reference to thread), unknown reason"); 01207 } 01208 } 01209 } 01210 01211 01212 /** Initialize Thread wrapper instance for main thread. 01213 * This will create an internal Thread instance such that it can be guaranteed that 01214 */ 01215 void 01216 Thread::init_main() 01217 { 01218 init_thread_key(); 01219 Thread *t = new Thread(MAIN_THREAD_NAME, pthread_self()); 01220 set_tsd_thread_instance(t); 01221 } 01222 01223 01224 /** Destroy main thread wrapper instance. 01225 * This destroys the thread wrapper created with init_main(). Note that 01226 * this has to be called from the very same thread that init_main() was called 01227 * from, which should be the main thread (somewhere from main() on). 01228 */ 01229 void 01230 Thread::destroy_main() 01231 { 01232 Thread *t = current_thread(); 01233 if ( strcmp(t->name(), MAIN_THREAD_NAME) == 0 ) { 01234 delete t; 01235 } else { 01236 throw Exception("Main thread can only be destroyed in main thread"); 01237 } 01238 } 01239 01240 01241 /** Get the ID of the currently running thread. 01242 * This will return the ID of the thread in which's context this method was 01243 * called. 01244 * @return ID of thread context 01245 */ 01246 pthread_t 01247 Thread::current_thread_id() 01248 { 01249 return pthread_self(); 01250 } 01251 01252 01253 /** Get the Thread instance of the currently running thread. 01254 * This will return the Thread instance of the thread in which's context this method was 01255 * called. 01256 * Note that only if the main application ensures to call init_main() it can be guaranteed 01257 * that this value is not NULL. 01258 * @return Thread instance of the current thread 01259 * @exception Exception thrown if this method is called before either init_main() is 01260 * called or any one thread has been started. 01261 */ 01262 Thread * 01263 Thread::current_thread() 01264 { 01265 if ( THREAD_KEY == PTHREAD_KEYS_MAX ) { 01266 throw Exception("No thread has been initialized"); 01267 } 01268 return (Thread *)pthread_getspecific(THREAD_KEY); 01269 } 01270 01271 01272 /** Similar to current_thread, but does never throw an exception. 01273 * This is a convenience method doing the same as current_thread(), but it never ever 01274 * throws an exception, rather it returns NULL in case of an error. This is necessary 01275 * if run from a C context. 01276 * @return Thread instance of the current thread 01277 */ 01278 Thread * 01279 Thread::current_thread_noexc() throw() 01280 { 01281 if ( THREAD_KEY == PTHREAD_KEYS_MAX ) { 01282 return 0; 01283 } 01284 return (Thread *)pthread_getspecific(THREAD_KEY); 01285 } 01286 01287 01288 /** Set the cancel state of the current thread. 01289 * The cancel state can only be set on the current thread. Please also 01290 * consider the documentation for pthread_setcancelstate(). 01291 * @param new_state new cancel state 01292 * @param old_state old cancel state 01293 */ 01294 void 01295 Thread::set_cancel_state(CancelState new_state, CancelState *old_state) 01296 { 01297 int oldstate = PTHREAD_CANCEL_ENABLE; 01298 int newstate = PTHREAD_CANCEL_ENABLE; 01299 if ( new_state == CANCEL_DISABLED ) { 01300 newstate = PTHREAD_CANCEL_DISABLE; 01301 } 01302 01303 pthread_setcancelstate(newstate, &oldstate); 01304 01305 if ( old_state != NULL ) { 01306 if ( oldstate == PTHREAD_CANCEL_DISABLE ) { 01307 *old_state = CANCEL_DISABLED; 01308 } else { 01309 *old_state = CANCEL_ENABLED; 01310 } 01311 } 01312 } 01313 01314 01315 } // end namespace fawkes