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 <omnithread.h>
60 #ifdef HAVE_SYS_TIME_H
61 // typedef of struct timeval and gettimeofday();
66 #if defined(__linux__) && defined(_MIT_POSIX_THREADS)
67 #include <pthread/mit/sys/timers.h>
70 #if defined(__irix__) && defined(PthreadSupportThreadPriority)
71 #if _POSIX_THREAD_PRIORITY_SCHEDULING
77 //#include <iostream.h> or #include <iostream> if DB is on.
79 #if (PthreadDraftVersion <= 6)
80 #define ERRNO(x) (((x) != 0) ? (errno) : 0)
82 // pthread_setprio returns old priority on success (draft version 4:
83 // OpenVms version < 7)
84 #define THROW_ERRORS(x) { if ((x) == -1) throw omni_thread_fatal(errno); }
86 #define THROW_ERRORS(x) { if ((x) != 0) throw omni_thread_fatal(errno); }
90 #define THROW_ERRORS(x) { int rc = (x); \
91 if (rc != 0) throw omni_thread_fatal(rc); }
96 ///////////////////////////////////////////////////////////////////////////
100 ///////////////////////////////////////////////////////////////////////////
103 omni_mutex::omni_mutex(void)
105 #if (PthreadDraftVersion == 4)
106 THROW_ERRORS(pthread_mutex_init(&posix_mutex, pthread_mutexattr_default));
108 THROW_ERRORS(pthread_mutex_init(&posix_mutex, 0));
112 omni_mutex::~omni_mutex(void)
114 THROW_ERRORS(pthread_mutex_destroy(&posix_mutex));
118 ///////////////////////////////////////////////////////////////////////////
120 // Condition variable
122 ///////////////////////////////////////////////////////////////////////////
125 omni_condition::omni_condition(omni_mutex* m) : mutex(m)
127 #if (PthreadDraftVersion == 4)
128 THROW_ERRORS(pthread_cond_init(&posix_cond, pthread_condattr_default));
130 THROW_ERRORS(pthread_cond_init(&posix_cond, 0));
134 omni_condition::~omni_condition(void)
136 THROW_ERRORS(pthread_cond_destroy(&posix_cond));
140 omni_condition::wait(void)
142 THROW_ERRORS(pthread_cond_wait(&posix_cond, &mutex->posix_mutex));
146 omni_condition::timedwait(unsigned long secs, unsigned long nanosecs)
148 timespec rqts = { secs, nanosecs };
151 int rc = ERRNO(pthread_cond_timedwait(&posix_cond,
152 &mutex->posix_mutex, &rqts));
156 #if (PthreadDraftVersion <= 6)
161 // Some versions of unix produces this errno when the wait was
162 // interrupted by a unix signal or fork.
163 // Some versions of the glibc 2.0.x produces this errno when the
164 // program is debugged under gdb. Straightly speaking this is non-posix
165 // compliant. We catch this here to make debugging possible.
172 throw omni_thread_fatal(rc);
179 omni_condition::signal(void)
181 THROW_ERRORS(pthread_cond_signal(&posix_cond));
185 omni_condition::broadcast(void)
187 THROW_ERRORS(pthread_cond_broadcast(&posix_cond));
192 ///////////////////////////////////////////////////////////////////////////
194 // Counting (or binary) semaphore
196 ///////////////////////////////////////////////////////////////////////////
199 omni_semaphore::omni_semaphore(unsigned int initial, unsigned int _max_count) : c(&m)
202 max_count = _max_count;
203 if (value < 0 || max_count < 1)
204 throw omni_thread_fatal(0);
207 omni_semaphore::~omni_semaphore(void)
212 omni_semaphore::wait(void)
214 omni_mutex_lock l(m);
223 omni_semaphore::trywait(void)
225 omni_mutex_lock l(m);
235 omni_semaphore::post(void)
238 omni_mutex_lock l(m);
239 if (value < max_count)
248 ///////////////////////////////////////////////////////////////////////////
252 ///////////////////////////////////////////////////////////////////////////
259 omni_mutex* omni_thread::next_id_mutex;
260 int omni_thread::next_id = 0;
262 static pthread_key_t self_key;
264 #ifdef PthreadSupportThreadPriority
265 static int lowest_priority;
266 static int normal_priority;
267 static int highest_priority;
270 #if defined(__osf1__) && defined(__alpha__) || defined(__VMS)
271 // omniORB requires a larger stack size than the default (21120) on OSF/1
272 static size_t stack_size = 32768;
273 #elif defined(__rtems__)
274 static size_t stack_size = ThreadStackSize;
275 #elif defined(__aix__)
276 static size_t stack_size = 262144;
278 static size_t stack_size = 0;
282 // Initialisation function (gets called before any user code).
285 static int& count() {
286 static int the_count = 0;
290 omni_thread::init_t::init_t(void)
292 if (count()++ != 0) // only do it once however many objects get created.
295 DB(cerr << "omni_thread::init: posix 1003.4a/1003.1c (draft "
296 << PthreadDraftVersion << ") implementation initialising\n");
298 #ifdef NeedPthreadInit
304 #if (PthreadDraftVersion == 4)
305 THROW_ERRORS(pthread_keycreate(&self_key, NULL));
307 THROW_ERRORS(pthread_key_create(&self_key, NULL));
310 #ifdef PthreadSupportThreadPriority
312 #if defined(__osf1__) && defined(__alpha__) || defined(__VMS)
314 lowest_priority = PRI_OTHER_MIN;
315 highest_priority = PRI_OTHER_MAX;
317 #elif defined(__hpux__)
319 lowest_priority = PRI_OTHER_MIN;
320 highest_priority = PRI_OTHER_MAX;
322 #elif defined(__sunos__) && (__OSVERSION__ == 5)
324 // a bug in pthread_attr_setschedparam means lowest priority is 1 not 0
327 highest_priority = 3;
331 lowest_priority = sched_get_priority_min(SCHED_FIFO);
332 highest_priority = sched_get_priority_max(SCHED_FIFO);
336 switch (highest_priority - lowest_priority) {
340 normal_priority = lowest_priority;
344 normal_priority = lowest_priority + 1;
348 #endif /* PthreadSupportThreadPriority */
350 next_id_mutex = new omni_mutex;
353 // Create object for this (i.e. initial) thread.
356 omni_thread* t = new omni_thread;
358 t->_state = STATE_RUNNING;
360 t->posix_thread = pthread_self ();
362 DB(cerr << "initial thread " << t->id() << endl);
364 THROW_ERRORS(pthread_setspecific(self_key, (void*)t));
366 #ifdef PthreadSupportThreadPriority
368 #if (PthreadDraftVersion == 4)
370 THROW_ERRORS(pthread_setprio(t->posix_thread,
371 posix_priority(PRIORITY_NORMAL)));
373 #elif (PthreadDraftVersion == 6)
376 pthread_attr_init(&attr);
378 THROW_ERRORS(pthread_attr_setprio(&attr, posix_priority(PRIORITY_NORMAL)));
380 THROW_ERRORS(pthread_setschedattr(t->posix_thread, attr));
384 struct sched_param sparam;
386 sparam.sched_priority = posix_priority(PRIORITY_NORMAL);
388 THROW_ERRORS(pthread_setschedparam(t->posix_thread, SCHED_OTHER, &sparam));
390 #endif /* PthreadDraftVersion */
392 #endif /* PthreadSupportThreadPriority */
395 omni_thread::init_t::~init_t(void)
397 if (--count() != 0) return;
399 omni_thread* self = omni_thread::self();
402 pthread_setspecific(self_key, 0);
405 delete next_id_mutex;
409 // Wrapper for thread creation.
413 omni_thread_wrapper(void* ptr)
415 omni_thread* me = (omni_thread*)ptr;
417 DB(cerr << "omni_thread_wrapper: thread " << me->id()
420 THROW_ERRORS(pthread_setspecific(self_key, me));
423 // Now invoke the thread function with the given argument.
426 if (me->fn_void != NULL) {
427 (*me->fn_void)(me->thread_arg);
431 if (me->fn_ret != NULL) {
432 void* return_value = (*me->fn_ret)(me->thread_arg);
433 omni_thread::exit(return_value);
437 me->run(me->thread_arg);
440 void* return_value = me->run_undetached(me->thread_arg);
441 omni_thread::exit(return_value);
444 // should never get here.
451 // Constructors for omni_thread - set up the thread object but don't
455 // construct a detached thread running a given function.
457 omni_thread::omni_thread(void (*fn)(void*), void* arg, priority_t pri)
459 common_constructor(arg, pri, 1);
464 // construct an undetached thread running a given function.
466 omni_thread::omni_thread(void* (*fn)(void*), void* arg, priority_t pri)
468 common_constructor(arg, pri, 0);
473 // construct a thread which will run either run() or run_undetached().
475 omni_thread::omni_thread(void* arg, priority_t pri)
477 common_constructor(arg, pri, 1);
482 // common part of all constructors.
485 omni_thread::common_constructor(void* arg, priority_t pri, int det)
490 next_id_mutex->lock();
492 next_id_mutex->unlock();
495 detached = det; // may be altered in start_undetached()
500 // posix_thread is set up in initialisation routine or start().
505 // Destructor for omni_thread.
508 omni_thread::~omni_thread(void)
510 DB(cerr << "destructor called for thread " << id() << endl);
512 for (key_t i=0; i < _value_alloc; i++) {
527 omni_thread::start(void)
529 omni_mutex_lock l(mutex);
531 if (_state != STATE_NEW)
532 throw omni_thread_invalid();
536 #if (PthreadDraftVersion == 4)
537 pthread_attr_create(&attr);
539 pthread_attr_init(&attr);
542 #if (PthreadDraftVersion == 8)
543 pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_UNDETACHED);
546 #ifdef PthreadSupportThreadPriority
548 #if (PthreadDraftVersion <= 6)
550 THROW_ERRORS(pthread_attr_setprio(&attr, posix_priority(_priority)));
554 struct sched_param sparam;
556 sparam.sched_priority = posix_priority(_priority);
558 THROW_ERRORS(pthread_attr_setschedparam(&attr, &sparam));
560 #endif /* PthreadDraftVersion */
562 #endif /* PthreadSupportThreadPriority */
564 #if !defined(__linux__)
566 THROW_ERRORS(pthread_attr_setstacksize(&attr, stack_size));
571 #if (PthreadDraftVersion == 4)
572 THROW_ERRORS(pthread_create(&posix_thread, attr, omni_thread_wrapper,
574 pthread_attr_delete(&attr);
576 THROW_ERRORS(pthread_create(&posix_thread, &attr, omni_thread_wrapper,
578 pthread_attr_destroy(&attr);
581 _state = STATE_RUNNING;
585 #if (PthreadDraftVersion <= 6)
586 THROW_ERRORS(pthread_detach(&posix_thread));
588 THROW_ERRORS(pthread_detach(posix_thread));
595 // Start a thread which will run the member function run_undetached().
599 omni_thread::start_undetached(void)
601 if ((fn_void != NULL) || (fn_ret != NULL))
602 throw omni_thread_invalid();
610 // join - simply check error conditions & call pthread_join.
614 omni_thread::join(void** status)
618 if ((_state != STATE_RUNNING) && (_state != STATE_TERMINATED)) {
620 throw omni_thread_invalid();
626 throw omni_thread_invalid();
629 throw omni_thread_invalid();
631 DB(cerr << "omni_thread::join: doing pthread_join\n");
633 THROW_ERRORS(pthread_join(posix_thread, status));
635 DB(cerr << "omni_thread::join: pthread_join succeeded\n");
637 #if (PthreadDraftVersion == 4)
638 // With draft 4 pthreads implementations (HPUX 10.x and
639 // Digital Unix 3.2), have to detach the thread after
640 // join. If not, the storage for the thread will not be
642 THROW_ERRORS(pthread_detach(&posix_thread));
650 // Change this thread's priority.
654 omni_thread::set_priority(priority_t pri)
656 omni_mutex_lock l(mutex);
658 if (_state != STATE_RUNNING)
659 throw omni_thread_invalid();
663 #ifdef PthreadSupportThreadPriority
665 #if (PthreadDraftVersion == 4)
667 THROW_ERRORS(pthread_setprio(posix_thread, posix_priority(pri)));
669 #elif (PthreadDraftVersion == 6)
672 pthread_attr_init(&attr);
674 THROW_ERRORS(pthread_attr_setprio(&attr, posix_priority(pri)));
676 THROW_ERRORS(pthread_setschedattr(posix_thread, attr));
680 struct sched_param sparam;
682 sparam.sched_priority = posix_priority(pri);
684 THROW_ERRORS(pthread_setschedparam(posix_thread, SCHED_OTHER, &sparam));
686 #endif /* PthreadDraftVersion */
688 #endif /* PthreadSupportThreadPriority */
693 // create - construct a new thread object and start it running. Returns thread
694 // object if successful, null pointer if not.
700 omni_thread::create(void (*fn)(void*), void* arg, priority_t pri)
702 omni_thread* t = new omni_thread(fn, arg, pri);
709 // undetached version
712 omni_thread::create(void* (*fn)(void*), void* arg, priority_t pri)
714 omni_thread* t = new omni_thread(fn, arg, pri);
723 // exit() _must_ lock the mutex even in the case of a detached thread. This is
724 // because a thread may run to completion before the thread that created it has
725 // had a chance to get out of start(). By locking the mutex we ensure that the
726 // creating thread must have reached the end of start() before we delete the
727 // thread object. Of course, once the call to start() returns, the user can
728 // still incorrectly refer to the thread object, but that's their problem.
732 omni_thread::exit(void* return_value)
734 omni_thread* me = self();
740 me->_state = STATE_TERMINATED;
744 DB(cerr << "omni_thread::exit: thread " << me->id() << " detached "
745 << me->detached << " return value " << return_value << endl);
752 DB(cerr << "omni_thread::exit: called with a non-omnithread. Exit quietly." << endl);
755 pthread_exit(return_value);
760 omni_thread::self(void)
764 #if (PthreadDraftVersion <= 6)
766 THROW_ERRORS(pthread_getspecific(self_key, (void**)&me));
770 me = (omni_thread *)pthread_getspecific(self_key);
775 // This thread is not created by omni_thread::start because it
776 // doesn't has a class omni_thread instance attached to its key.
777 DB(cerr << "omni_thread::self: called with a non-omnithread. NULL is returned." << endl);
785 omni_thread::yield(void)
787 #if (PthreadDraftVersion == 6)
791 #elif (PthreadDraftVersion < 9)
797 THROW_ERRORS(sched_yield());
804 omni_thread::sleep(unsigned long secs, unsigned long nanosecs)
806 timespec rqts = { secs, nanosecs };
811 while (nanosleep(&rqts, &remain)) {
812 if (errno == EINTR) {
813 rqts.tv_sec = remain.tv_sec;
814 rqts.tv_nsec = remain.tv_nsec;
818 throw omni_thread_fatal(errno);
822 #if defined(__osf1__) && defined(__alpha__) || defined(__hpux__) && (__OSVERSION__ == 10) || defined(__VMS) || defined(__SINIX__) || defined (__POSIX_NT__)
824 if (pthread_delay_np(&rqts) != 0)
825 throw omni_thread_fatal(errno);
827 #elif defined(__linux__) || defined(__aix__)
830 while ((secs = ::sleep(secs))) ;
832 usleep(secs * 1000000 + (nanosecs / 1000));
835 #elif defined(__darwin__) || defined(__macos__)
837 // Single UNIX Specification says argument of usleep() must be
838 // less than 1,000,000.
839 secs += nanosecs / 1000000000;
840 nanosecs %= 1000000000;
841 while ((secs = ::sleep(secs))) ;
842 usleep(nanosecs / 1000);
846 throw omni_thread_invalid();
849 #endif /* NoNanoSleep */
854 omni_thread::get_time(unsigned long* abs_sec, unsigned long* abs_nsec,
855 unsigned long rel_sec, unsigned long rel_nsec)
859 #if defined(__osf1__) && defined(__alpha__) || defined(__hpux__) && (__OSVERSION__ == 10) || defined(__VMS) || defined(__SINIX__) || defined(__POSIX_NT__)
862 rel.tv_sec = rel_sec;
863 rel.tv_nsec = rel_nsec;
864 THROW_ERRORS(pthread_get_expiration_np(&rel, &abs));
868 #ifdef HAVE_CLOCK_GETTIME /* __linux__ || __aix__ */
870 clock_gettime(CLOCK_REALTIME, &abs);
872 #elif defined(HAVE_GETTIMEOFDAY) /* defined(__linux__) || defined(__aix__) || defined(__SCO_VERSION__) || defined(__darwin__) || defined(__macos__) */
875 gettimeofday(&tv, NULL);
876 abs.tv_sec = tv.tv_sec;
877 abs.tv_nsec = tv.tv_usec * 1000;
880 #error no get time support
881 #endif /* __linux__ || __aix__ */
883 abs.tv_nsec += rel_nsec;
884 abs.tv_sec += rel_sec + abs.tv_nsec / 1000000000;
885 abs.tv_nsec = abs.tv_nsec % 1000000000;
887 #endif /* __osf1__ && __alpha__ */
889 *abs_sec = abs.tv_sec;
890 *abs_nsec = abs.tv_nsec;
895 omni_thread::posix_priority(priority_t pri)
897 #ifdef PthreadSupportThreadPriority
901 return lowest_priority;
903 case PRIORITY_NORMAL:
904 return normal_priority;
907 return highest_priority;
912 throw omni_thread_invalid();
919 omni_thread::stacksize(unsigned long sz)
925 omni_thread::stacksize()
934 class omni_thread_dummy : public omni_thread {
936 inline omni_thread_dummy() : omni_thread()
939 _state = STATE_RUNNING;
940 posix_thread = pthread_self();
941 THROW_ERRORS(pthread_setspecific(self_key, (void*)this));
943 inline ~omni_thread_dummy()
945 THROW_ERRORS(pthread_setspecific(self_key, 0));
950 omni_thread::create_dummy()
952 if (omni_thread::self())
953 throw omni_thread_invalid();
955 return new omni_thread_dummy;
959 omni_thread::release_dummy()
961 omni_thread* self = omni_thread::self();
962 if (!self || !self->_dummy)
963 throw omni_thread_invalid();
965 omni_thread_dummy* dummy = (omni_thread_dummy*)self;
970 #define INSIDE_THREAD_IMPL_CC
971 #include "threaddata.cc"
972 #undef INSIDE_THREAD_IMPL_CC