1 // Package : omnithread
2 // omnithread/posix.cc Created : 7/94 tjr
4 // Copyright (C) 2006 Free Software Foundation, Inc.
5 // Copyright (C) 1994-1999 AT&T Laboratories Cambridge
7 // This file is part of the omnithread library
9 // The omnithread library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Library General Public
11 // License as published by the Free Software Foundation; either
12 // version 2 of the License, or (at your option) any later version.
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Library General Public License for more details.
19 // You should have received a copy of the GNU Library General Public
20 // License along with this library; if not, write to the Free
21 // Software Foundation, Inc., 51 Franklin Street, Boston, MA
26 // Implementation of OMNI thread abstraction for posix threads
28 // The source below tests for the definition of the macros:
29 // PthreadDraftVersion
30 // PthreadSupportThreadPriority
34 // As different draft versions of the pthread standard P1003.4a/P1003.1c
35 // define slightly different APIs, the macro 'PthreadDraftVersion'
36 // identifies the draft version supported by this particular platform.
38 // Some unix variants do not support thread priority unless a real-time
39 // kernel option is installed. The macro 'PthreadSupportThreadPriority',
40 // if defined, enables the use of thread priority. If it is not defined,
41 // setting or changing thread priority will be silently ignored.
43 // nanosleep() is defined in Posix P1003.4 since Draft 9 (?).
44 // Not all platforms support this standard. The macro 'NoNanoSleep'
45 // identifies platform that don't.
52 #include <gnuradio/omnithread.h>
54 #if (PthreadDraftVersion == 0)
55 #error "PthreadDraftVersion not defined. If not sure, define it to 10"
64 #ifdef HAVE_SYS_TIME_H
65 // typedef of struct timeval and gettimeofday();
70 #if defined(__linux__) && defined(_MIT_POSIX_THREADS)
71 #include <pthread/mit/sys/timers.h>
74 #if defined(__irix__) && defined(PthreadSupportThreadPriority)
75 #if _POSIX_THREAD_PRIORITY_SCHEDULING
89 #if (PthreadDraftVersion <= 6)
90 #define ERRNO(x) (((x) != 0) ? (errno) : 0)
92 // pthread_setprio returns old priority on success (draft version 4:
93 // OpenVms version < 7)
94 #define THROW_ERRORS(x) { if ((x) == -1) throw omni_thread_fatal(errno); }
96 #define THROW_ERRORS(x) { if ((x) != 0) throw omni_thread_fatal(errno); }
100 #define THROW_ERRORS(x) { int rc = (x); \
101 if (rc != 0) throw omni_thread_fatal(rc); }
106 ///////////////////////////////////////////////////////////////////////////
110 ///////////////////////////////////////////////////////////////////////////
113 omni_mutex::omni_mutex(void)
115 #if (PthreadDraftVersion == 4)
116 THROW_ERRORS(pthread_mutex_init(&posix_mutex, pthread_mutexattr_default));
118 THROW_ERRORS(pthread_mutex_init(&posix_mutex, 0));
122 omni_mutex::~omni_mutex(void)
124 THROW_ERRORS(pthread_mutex_destroy(&posix_mutex));
128 ///////////////////////////////////////////////////////////////////////////
130 // Condition variable
132 ///////////////////////////////////////////////////////////////////////////
135 omni_condition::omni_condition(omni_mutex* m) : mutex(m)
137 #if (PthreadDraftVersion == 4)
138 THROW_ERRORS(pthread_cond_init(&posix_cond, pthread_condattr_default));
140 THROW_ERRORS(pthread_cond_init(&posix_cond, 0));
144 omni_condition::~omni_condition(void)
146 THROW_ERRORS(pthread_cond_destroy(&posix_cond));
150 omni_condition::wait(void)
152 THROW_ERRORS(pthread_cond_wait(&posix_cond, &mutex->posix_mutex));
156 omni_condition::timedwait(unsigned long secs, unsigned long nanosecs)
158 timespec rqts = { secs, nanosecs };
161 int rc = ERRNO(pthread_cond_timedwait(&posix_cond,
162 &mutex->posix_mutex, &rqts));
166 #if (PthreadDraftVersion <= 6)
171 // Some versions of unix produces this errno when the wait was
172 // interrupted by a unix signal or fork.
173 // Some versions of the glibc 2.0.x produces this errno when the
174 // program is debugged under gdb. Straightly speaking this is non-posix
175 // compliant. We catch this here to make debugging possible.
182 throw omni_thread_fatal(rc);
189 omni_condition::signal(void)
191 THROW_ERRORS(pthread_cond_signal(&posix_cond));
195 omni_condition::broadcast(void)
197 THROW_ERRORS(pthread_cond_broadcast(&posix_cond));
202 ///////////////////////////////////////////////////////////////////////////
204 // Counting (or binary) semaphore
206 ///////////////////////////////////////////////////////////////////////////
209 omni_semaphore::omni_semaphore(unsigned int initial, unsigned int _max_count) : c(&m)
212 max_count = _max_count;
213 if (value < 0 || max_count < 1)
214 throw omni_thread_fatal(0);
217 omni_semaphore::~omni_semaphore(void)
222 omni_semaphore::wait(void)
224 omni_mutex_lock l(m);
233 omni_semaphore::trywait(void)
235 omni_mutex_lock l(m);
245 omni_semaphore::post(void)
248 omni_mutex_lock l(m);
249 if (value < max_count)
258 ///////////////////////////////////////////////////////////////////////////
262 ///////////////////////////////////////////////////////////////////////////
269 omni_mutex* omni_thread::next_id_mutex;
270 int omni_thread::next_id = 0;
272 static pthread_key_t self_key;
274 #ifdef PthreadSupportThreadPriority
275 static int lowest_priority;
276 static int normal_priority;
277 static int highest_priority;
280 #if defined(__osf1__) && defined(__alpha__) || defined(__VMS)
281 // omniORB requires a larger stack size than the default (21120) on OSF/1
282 static size_t stack_size = 32768;
283 #elif defined(__rtems__)
284 static size_t stack_size = ThreadStackSize;
285 #elif defined(__aix__)
286 static size_t stack_size = 262144;
288 static size_t stack_size = 0;
292 // Initialisation function (gets called before any user code).
295 static int& count() {
296 static int the_count = 0;
300 omni_thread::init_t::init_t(void)
302 if (count()++ != 0) // only do it once however many objects get created.
305 DB(cerr << "omni_thread::init: posix 1003.4a/1003.1c (draft "
306 << PthreadDraftVersion << ") implementation initialising\n");
308 #ifdef NeedPthreadInit
314 #if (PthreadDraftVersion == 4)
315 THROW_ERRORS(pthread_keycreate(&self_key, NULL));
317 THROW_ERRORS(pthread_key_create(&self_key, NULL));
320 #ifdef PthreadSupportThreadPriority
322 #if defined(__osf1__) && defined(__alpha__) || defined(__VMS)
324 lowest_priority = PRI_OTHER_MIN;
325 highest_priority = PRI_OTHER_MAX;
327 #elif defined(__hpux__)
329 lowest_priority = PRI_OTHER_MIN;
330 highest_priority = PRI_OTHER_MAX;
332 #elif defined(__sunos__) && (__OSVERSION__ == 5)
334 // a bug in pthread_attr_setschedparam means lowest priority is 1 not 0
337 highest_priority = 3;
341 lowest_priority = sched_get_priority_min(SCHED_FIFO);
342 highest_priority = sched_get_priority_max(SCHED_FIFO);
346 switch (highest_priority - lowest_priority) {
350 normal_priority = lowest_priority;
354 normal_priority = lowest_priority + 1;
358 #endif /* PthreadSupportThreadPriority */
360 next_id_mutex = new omni_mutex;
363 // Create object for this (i.e. initial) thread.
366 omni_thread* t = new omni_thread;
368 t->_state = STATE_RUNNING;
370 t->posix_thread = pthread_self ();
372 DB(cerr << "initial thread " << t->id() << endl);
374 THROW_ERRORS(pthread_setspecific(self_key, (void*)t));
376 #ifdef PthreadSupportThreadPriority
378 #if (PthreadDraftVersion == 4)
380 THROW_ERRORS(pthread_setprio(t->posix_thread,
381 posix_priority(PRIORITY_NORMAL)));
383 #elif (PthreadDraftVersion == 6)
386 pthread_attr_init(&attr);
388 THROW_ERRORS(pthread_attr_setprio(&attr, posix_priority(PRIORITY_NORMAL)));
390 THROW_ERRORS(pthread_setschedattr(t->posix_thread, attr));
394 struct sched_param sparam;
396 sparam.sched_priority = posix_priority(PRIORITY_NORMAL);
398 THROW_ERRORS(pthread_setschedparam(t->posix_thread, SCHED_OTHER, &sparam));
400 #endif /* PthreadDraftVersion */
402 #endif /* PthreadSupportThreadPriority */
405 omni_thread::init_t::~init_t(void)
407 if (--count() != 0) return;
409 omni_thread* self = omni_thread::self();
412 pthread_setspecific(self_key, 0);
415 delete next_id_mutex;
419 // Wrapper for thread creation.
423 omni_thread_wrapper(void* ptr)
425 omni_thread* me = (omni_thread*)ptr;
427 DB(cerr << "omni_thread_wrapper: thread " << me->id()
430 THROW_ERRORS(pthread_setspecific(self_key, me));
433 // Now invoke the thread function with the given argument.
436 if (me->fn_void != NULL) {
437 (*me->fn_void)(me->thread_arg);
441 if (me->fn_ret != NULL) {
442 void* return_value = (*me->fn_ret)(me->thread_arg);
443 omni_thread::exit(return_value);
447 me->run(me->thread_arg);
450 void* return_value = me->run_undetached(me->thread_arg);
451 omni_thread::exit(return_value);
454 // should never get here.
461 // Constructors for omni_thread - set up the thread object but don't
465 // construct a detached thread running a given function.
467 omni_thread::omni_thread(void (*fn)(void*), void* arg, priority_t pri)
469 common_constructor(arg, pri, 1);
474 // construct an undetached thread running a given function.
476 omni_thread::omni_thread(void* (*fn)(void*), void* arg, priority_t pri)
478 common_constructor(arg, pri, 0);
483 // construct a thread which will run either run() or run_undetached().
485 omni_thread::omni_thread(void* arg, priority_t pri)
487 common_constructor(arg, pri, 1);
492 // common part of all constructors.
495 omni_thread::common_constructor(void* arg, priority_t pri, int det)
500 next_id_mutex->lock();
502 next_id_mutex->unlock();
505 detached = det; // may be altered in start_undetached()
510 // posix_thread is set up in initialisation routine or start().
515 // Destructor for omni_thread.
518 omni_thread::~omni_thread(void)
520 DB(cerr << "destructor called for thread " << id() << endl);
522 for (key_t i=0; i < _value_alloc; i++) {
537 omni_thread::start(void)
539 omni_mutex_lock l(mutex);
541 if (_state != STATE_NEW)
542 throw omni_thread_invalid();
546 #if (PthreadDraftVersion == 4)
547 pthread_attr_create(&attr);
549 pthread_attr_init(&attr);
552 #if (PthreadDraftVersion == 8)
553 pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_UNDETACHED);
556 #ifdef PthreadSupportThreadPriority
558 #if (PthreadDraftVersion <= 6)
560 THROW_ERRORS(pthread_attr_setprio(&attr, posix_priority(_priority)));
564 struct sched_param sparam;
566 sparam.sched_priority = posix_priority(_priority);
568 THROW_ERRORS(pthread_attr_setschedparam(&attr, &sparam));
570 #endif /* PthreadDraftVersion */
572 #endif /* PthreadSupportThreadPriority */
574 #if !defined(__linux__)
576 THROW_ERRORS(pthread_attr_setstacksize(&attr, stack_size));
581 #if (PthreadDraftVersion == 4)
582 THROW_ERRORS(pthread_create(&posix_thread, attr, omni_thread_wrapper,
584 pthread_attr_delete(&attr);
586 THROW_ERRORS(pthread_create(&posix_thread, &attr, omni_thread_wrapper,
588 pthread_attr_destroy(&attr);
591 _state = STATE_RUNNING;
595 #if (PthreadDraftVersion <= 6)
596 THROW_ERRORS(pthread_detach(&posix_thread));
598 THROW_ERRORS(pthread_detach(posix_thread));
605 // Start a thread which will run the member function run_undetached().
609 omni_thread::start_undetached(void)
611 if ((fn_void != NULL) || (fn_ret != NULL))
612 throw omni_thread_invalid();
620 // join - simply check error conditions & call pthread_join.
624 omni_thread::join(void** status)
628 if ((_state != STATE_RUNNING) && (_state != STATE_TERMINATED)) {
630 throw omni_thread_invalid();
636 throw omni_thread_invalid();
639 throw omni_thread_invalid();
641 DB(cerr << "omni_thread::join: doing pthread_join\n");
643 THROW_ERRORS(pthread_join(posix_thread, status));
645 DB(cerr << "omni_thread::join: pthread_join succeeded\n");
647 #if (PthreadDraftVersion == 4)
648 // With draft 4 pthreads implementations (HPUX 10.x and
649 // Digital Unix 3.2), have to detach the thread after
650 // join. If not, the storage for the thread will not be
652 THROW_ERRORS(pthread_detach(&posix_thread));
660 // Change this thread's priority.
664 omni_thread::set_priority(priority_t pri)
666 omni_mutex_lock l(mutex);
668 if (_state != STATE_RUNNING)
669 throw omni_thread_invalid();
673 #ifdef PthreadSupportThreadPriority
675 #if (PthreadDraftVersion == 4)
677 THROW_ERRORS(pthread_setprio(posix_thread, posix_priority(pri)));
679 #elif (PthreadDraftVersion == 6)
682 pthread_attr_init(&attr);
684 THROW_ERRORS(pthread_attr_setprio(&attr, posix_priority(pri)));
686 THROW_ERRORS(pthread_setschedattr(posix_thread, attr));
690 struct sched_param sparam;
692 sparam.sched_priority = posix_priority(pri);
694 THROW_ERRORS(pthread_setschedparam(posix_thread, SCHED_OTHER, &sparam));
696 #endif /* PthreadDraftVersion */
698 #endif /* PthreadSupportThreadPriority */
703 // create - construct a new thread object and start it running. Returns thread
704 // object if successful, null pointer if not.
710 omni_thread::create(void (*fn)(void*), void* arg, priority_t pri)
712 omni_thread* t = new omni_thread(fn, arg, pri);
719 // undetached version
722 omni_thread::create(void* (*fn)(void*), void* arg, priority_t pri)
724 omni_thread* t = new omni_thread(fn, arg, pri);
733 // exit() _must_ lock the mutex even in the case of a detached thread. This is
734 // because a thread may run to completion before the thread that created it has
735 // had a chance to get out of start(). By locking the mutex we ensure that the
736 // creating thread must have reached the end of start() before we delete the
737 // thread object. Of course, once the call to start() returns, the user can
738 // still incorrectly refer to the thread object, but that's their problem.
742 omni_thread::exit(void* return_value)
744 omni_thread* me = self();
750 me->_state = STATE_TERMINATED;
754 DB(cerr << "omni_thread::exit: thread " << me->id() << " detached "
755 << me->detached << " return value " << return_value << endl);
762 DB(cerr << "omni_thread::exit: called with a non-omnithread. Exit quietly." << endl);
765 pthread_exit(return_value);
770 omni_thread::self(void)
774 #if (PthreadDraftVersion <= 6)
776 THROW_ERRORS(pthread_getspecific(self_key, (void**)&me));
780 me = (omni_thread *)pthread_getspecific(self_key);
785 // This thread is not created by omni_thread::start because it
786 // doesn't has a class omni_thread instance attached to its key.
787 DB(cerr << "omni_thread::self: called with a non-omnithread. NULL is returned." << endl);
795 omni_thread::yield(void)
797 #if (PthreadDraftVersion == 6)
801 #elif (PthreadDraftVersion < 9)
807 THROW_ERRORS(sched_yield());
814 omni_thread::sleep(unsigned long secs, unsigned long nanosecs)
816 timespec rqts = { secs, nanosecs };
821 while (nanosleep(&rqts, &remain)) {
822 if (errno == EINTR) {
823 rqts.tv_sec = remain.tv_sec;
824 rqts.tv_nsec = remain.tv_nsec;
828 throw omni_thread_fatal(errno);
832 #if defined(__osf1__) && defined(__alpha__) || defined(__hpux__) && (__OSVERSION__ == 10) || defined(__VMS) || defined(__SINIX__) || defined (__POSIX_NT__)
834 if (pthread_delay_np(&rqts) != 0)
835 throw omni_thread_fatal(errno);
837 #elif defined(__linux__) || defined(__aix__)
840 while ((secs = ::sleep(secs))) ;
842 usleep(secs * 1000000 + (nanosecs / 1000));
845 #elif defined(__darwin__) || defined(__macos__)
847 // Single UNIX Specification says argument of usleep() must be
848 // less than 1,000,000.
849 secs += nanosecs / 1000000000;
850 nanosecs %= 1000000000;
851 while ((secs = ::sleep(secs))) ;
852 usleep(nanosecs / 1000);
856 throw omni_thread_invalid();
859 #endif /* NoNanoSleep */
864 omni_thread::get_time(unsigned long* abs_sec, unsigned long* abs_nsec,
865 unsigned long rel_sec, unsigned long rel_nsec)
869 #if defined(__osf1__) && defined(__alpha__) || defined(__hpux__) && (__OSVERSION__ == 10) || defined(__VMS) || defined(__SINIX__) || defined(__POSIX_NT__)
872 rel.tv_sec = rel_sec;
873 rel.tv_nsec = rel_nsec;
874 THROW_ERRORS(pthread_get_expiration_np(&rel, &abs));
878 #ifdef HAVE_CLOCK_GETTIME /* __linux__ || __aix__ */
880 clock_gettime(CLOCK_REALTIME, &abs);
882 #elif defined(HAVE_GETTIMEOFDAY) /* defined(__linux__) || defined(__aix__) || defined(__SCO_VERSION__) || defined(__darwin__) || defined(__macos__) */
885 gettimeofday(&tv, NULL);
886 abs.tv_sec = tv.tv_sec;
887 abs.tv_nsec = tv.tv_usec * 1000;
890 #error no get time support
891 #endif /* __linux__ || __aix__ */
893 abs.tv_nsec += rel_nsec;
894 abs.tv_sec += rel_sec + abs.tv_nsec / 1000000000;
895 abs.tv_nsec = abs.tv_nsec % 1000000000;
897 #endif /* __osf1__ && __alpha__ */
899 *abs_sec = abs.tv_sec;
900 *abs_nsec = abs.tv_nsec;
905 omni_thread::posix_priority(priority_t pri)
907 #ifdef PthreadSupportThreadPriority
911 return lowest_priority;
913 case PRIORITY_NORMAL:
914 return normal_priority;
917 return highest_priority;
922 throw omni_thread_invalid();
929 omni_thread::stacksize(unsigned long sz)
935 omni_thread::stacksize()
944 class omni_thread_dummy : public omni_thread {
946 inline omni_thread_dummy() : omni_thread()
949 _state = STATE_RUNNING;
950 posix_thread = pthread_self();
951 THROW_ERRORS(pthread_setspecific(self_key, (void*)this));
953 inline ~omni_thread_dummy()
955 THROW_ERRORS(pthread_setspecific(self_key, 0));
960 omni_thread::create_dummy()
962 if (omni_thread::self())
963 throw omni_thread_invalid();
965 return new omni_thread_dummy;
969 omni_thread::release_dummy()
971 omni_thread* self = omni_thread::self();
972 if (!self || !self->_dummy)
973 throw omni_thread_invalid();
975 omni_thread_dummy* dummy = (omni_thread_dummy*)self;
980 #define INSIDE_THREAD_IMPL_CC
981 #include "threaddata.cc"
982 #undef INSIDE_THREAD_IMPL_CC