1 // Package : omnithread
2 // omnithread/nt.cc Created : 6/95 tjr
4 // Copyright (C) 2006 Free Software Foundation, Inc.
5 // Copyright (C) 1995-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 NT threads
35 #include <omnithread.h>
39 //#include <iostream.h> or #include <iostream> if DB is on.
41 static void get_time_now(unsigned long* abs_sec, unsigned long* abs_nsec);
43 ///////////////////////////////////////////////////////////////////////////
47 ///////////////////////////////////////////////////////////////////////////
50 omni_mutex::omni_mutex(void)
52 InitializeCriticalSection(&crit);
55 omni_mutex::~omni_mutex(void)
57 DeleteCriticalSection(&crit);
62 ///////////////////////////////////////////////////////////////////////////
66 ///////////////////////////////////////////////////////////////////////////
70 // Condition variables are tricky to implement using NT synchronisation
71 // primitives, since none of them have the atomic "release mutex and wait to be
72 // signalled" which is central to the idea of a condition variable. To get
73 // around this the solution is to record which threads are waiting and
74 // explicitly wake up those threads.
76 // Here we implement a condition variable using a list of waiting threads
77 // (protected by a critical section), and a per-thread semaphore (which
78 // actually only needs to be a binary semaphore).
80 // To wait on the cv, a thread puts itself on the list of waiting threads for
81 // that cv, then releases the mutex and waits on its own personal semaphore. A
82 // signalling thread simply takes a thread from the head of the list and kicks
83 // that thread's semaphore. Broadcast is simply implemented by kicking the
84 // semaphore of each waiting thread.
86 // The only other tricky part comes when a thread gets a timeout from a timed
87 // wait on its semaphore. Between returning with a timeout from the wait and
88 // entering the critical section, a signalling thread could get in, kick the
89 // waiting thread's semaphore and remove it from the list. If this happens,
90 // the waiting thread's semaphore is now out of step so it needs resetting, and
91 // the thread should indicate that it was signalled rather than that it timed
94 // It is possible that the thread calling wait or timedwait is not a
95 // omni_thread. In this case we have to provide a temporary data structure,
96 // i.e. for the duration of the call, for the thread to link itself on the
97 // list of waiting threads. _internal_omni_thread_dummy provides such
98 // a data structure and _internal_omni_thread_helper is a helper class to
99 // deal with this special case for wait() and timedwait(). Once created,
100 // the _internal_omni_thread_dummy is cached for use by the next wait() or
101 // timedwait() call from a non-omni_thread. This is probably worth doing
102 // because creating a Semaphore is quite heavy weight.
104 class _internal_omni_thread_helper;
106 class _internal_omni_thread_dummy : public omni_thread {
108 inline _internal_omni_thread_dummy() : next(0) { }
109 inline ~_internal_omni_thread_dummy() { }
110 friend class _internal_omni_thread_helper;
112 _internal_omni_thread_dummy* next;
115 class _internal_omni_thread_helper {
117 inline _internal_omni_thread_helper() {
119 t = omni_thread::self();
121 omni_mutex_lock sync(cachelock);
127 d = new _internal_omni_thread_dummy;
132 inline ~_internal_omni_thread_helper() {
134 omni_mutex_lock sync(cachelock);
139 inline operator omni_thread* () { return t; }
140 inline omni_thread* operator->() { return t; }
142 static _internal_omni_thread_dummy* cache;
143 static omni_mutex cachelock;
146 _internal_omni_thread_dummy* d;
150 _internal_omni_thread_dummy* _internal_omni_thread_helper::cache = 0;
151 omni_mutex _internal_omni_thread_helper::cachelock;
154 omni_condition::omni_condition(omni_mutex* m) : mutex(m)
156 InitializeCriticalSection(&crit);
157 waiting_head = waiting_tail = NULL;
161 omni_condition::~omni_condition(void)
163 DeleteCriticalSection(&crit);
164 DB( if (waiting_head != NULL) {
165 cerr << "omni_condition::~omni_condition: list of waiting threads "
172 omni_condition::wait(void)
174 _internal_omni_thread_helper me;
176 EnterCriticalSection(&crit);
178 me->cond_next = NULL;
179 me->cond_prev = waiting_tail;
180 if (waiting_head == NULL)
183 waiting_tail->cond_next = me;
185 me->cond_waiting = TRUE;
187 LeaveCriticalSection(&crit);
191 DWORD result = WaitForSingleObject(me->cond_semaphore, INFINITE);
195 if (result != WAIT_OBJECT_0)
196 throw omni_thread_fatal(GetLastError());
201 omni_condition::timedwait(unsigned long abs_sec, unsigned long abs_nsec)
203 _internal_omni_thread_helper me;
205 EnterCriticalSection(&crit);
207 me->cond_next = NULL;
208 me->cond_prev = waiting_tail;
209 if (waiting_head == NULL)
212 waiting_tail->cond_next = me;
214 me->cond_waiting = TRUE;
216 LeaveCriticalSection(&crit);
220 unsigned long now_sec, now_nsec;
222 get_time_now(&now_sec, &now_nsec);
225 if ((abs_sec <= now_sec) && ((abs_sec < now_sec) || (abs_nsec < now_nsec)))
228 timeout = (abs_sec-now_sec) * 1000;
230 if( abs_nsec < now_nsec ) timeout -= (now_nsec-abs_nsec) / 1000000;
231 else timeout += (abs_nsec-now_nsec) / 1000000;
234 DWORD result = WaitForSingleObject(me->cond_semaphore, timeout);
236 if (result == WAIT_TIMEOUT) {
237 EnterCriticalSection(&crit);
239 if (me->cond_waiting) {
240 if (me->cond_prev != NULL)
241 me->cond_prev->cond_next = me->cond_next;
243 waiting_head = me->cond_next;
244 if (me->cond_next != NULL)
245 me->cond_next->cond_prev = me->cond_prev;
247 waiting_tail = me->cond_prev;
248 me->cond_waiting = FALSE;
250 LeaveCriticalSection(&crit);
257 // We timed out but another thread still signalled us. Wait for
258 // the semaphore (it _must_ have been signalled) to decrement it
259 // again. Return that we were signalled, not that we timed out.
262 LeaveCriticalSection(&crit);
264 result = WaitForSingleObject(me->cond_semaphore, INFINITE);
267 if (result != WAIT_OBJECT_0)
268 throw omni_thread_fatal(GetLastError());
276 omni_condition::signal(void)
278 EnterCriticalSection(&crit);
280 if (waiting_head != NULL) {
281 omni_thread* t = waiting_head;
282 waiting_head = t->cond_next;
283 if (waiting_head == NULL)
286 waiting_head->cond_prev = NULL;
287 t->cond_waiting = FALSE;
289 if (!ReleaseSemaphore(t->cond_semaphore, 1, NULL)) {
290 int rc = GetLastError();
291 LeaveCriticalSection(&crit);
292 throw omni_thread_fatal(rc);
296 LeaveCriticalSection(&crit);
301 omni_condition::broadcast(void)
303 EnterCriticalSection(&crit);
305 while (waiting_head != NULL) {
306 omni_thread* t = waiting_head;
307 waiting_head = t->cond_next;
308 if (waiting_head == NULL)
311 waiting_head->cond_prev = NULL;
312 t->cond_waiting = FALSE;
314 if (!ReleaseSemaphore(t->cond_semaphore, 1, NULL)) {
315 int rc = GetLastError();
316 LeaveCriticalSection(&crit);
317 throw omni_thread_fatal(rc);
321 LeaveCriticalSection(&crit);
326 ///////////////////////////////////////////////////////////////////////////
328 // Counting semaphore
330 ///////////////////////////////////////////////////////////////////////////
333 #define SEMAPHORE_MAX 0x7fffffff
336 omni_semaphore::omni_semaphore(unsigned int initial, unsigned int max_count)
338 if (max_count > SEMAPHORE_MAX)
339 max_count= SEMAPHORE_MAX;
341 nt_sem = CreateSemaphore(NULL, initial, max_count, NULL);
343 if (nt_sem == NULL) {
344 DB( cerr << "omni_semaphore::omni_semaphore: CreateSemaphore error "
345 << GetLastError() << endl );
346 throw omni_thread_fatal(GetLastError());
351 omni_semaphore::~omni_semaphore(void)
353 if (!CloseHandle(nt_sem)) {
354 DB( cerr << "omni_semaphore::~omni_semaphore: CloseHandle error "
355 << GetLastError() << endl );
356 throw omni_thread_fatal(GetLastError());
362 omni_semaphore::wait(void)
364 if (WaitForSingleObject(nt_sem, INFINITE) != WAIT_OBJECT_0)
365 throw omni_thread_fatal(GetLastError());
370 omni_semaphore::trywait(void)
372 switch (WaitForSingleObject(nt_sem, 0)) {
380 throw omni_thread_fatal(GetLastError());
381 return 0; /* keep msvc++ happy */
386 omni_semaphore::post(void)
388 if (!ReleaseSemaphore(nt_sem, 1, NULL))
389 throw omni_thread_fatal(GetLastError());
394 ///////////////////////////////////////////////////////////////////////////
398 ///////////////////////////////////////////////////////////////////////////
405 omni_mutex* omni_thread::next_id_mutex;
406 int omni_thread::next_id = 0;
407 static DWORD self_tls_index;
409 static unsigned int stack_size = 0;
412 // Initialisation function (gets called before any user code).
415 static int& count() {
416 static int the_count = 0;
420 omni_thread::init_t::init_t(void)
422 if (count()++ != 0) // only do it once however many objects get created.
425 DB(cerr << "omni_thread::init: NT implementation initialising\n");
427 self_tls_index = TlsAlloc();
429 if (self_tls_index == 0xffffffff)
430 throw omni_thread_fatal(GetLastError());
432 next_id_mutex = new omni_mutex;
435 // Create object for this (i.e. initial) thread.
438 omni_thread* t = new omni_thread;
440 t->_state = STATE_RUNNING;
442 if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
443 GetCurrentProcess(), &t->handle,
444 0, FALSE, DUPLICATE_SAME_ACCESS))
445 throw omni_thread_fatal(GetLastError());
447 t->nt_id = GetCurrentThreadId();
449 DB(cerr << "initial thread " << t->id() << " NT thread id " << t->nt_id
452 if (!TlsSetValue(self_tls_index, (LPVOID)t))
453 throw omni_thread_fatal(GetLastError());
455 if (!SetThreadPriority(t->handle, nt_priority(PRIORITY_NORMAL)))
456 throw omni_thread_fatal(GetLastError());
459 omni_thread::init_t::~init_t(void)
461 if (--count() != 0) return;
463 omni_thread* self = omni_thread::self();
466 TlsSetValue(self_tls_index, (LPVOID)0);
469 delete next_id_mutex;
471 TlsFree(self_tls_index);
475 // Wrapper for thread creation.
479 #ifndef __BCPLUSPLUS__
484 omni_thread_wrapper(void* ptr)
486 omni_thread* me = (omni_thread*)ptr;
488 DB(cerr << "omni_thread_wrapper: thread " << me->id()
491 if (!TlsSetValue(self_tls_index, (LPVOID)me))
492 throw omni_thread_fatal(GetLastError());
495 // Now invoke the thread function with the given argument.
498 if (me->fn_void != NULL) {
499 (*me->fn_void)(me->thread_arg);
503 if (me->fn_ret != NULL) {
504 void* return_value = (*me->fn_ret)(me->thread_arg);
505 omni_thread::exit(return_value);
509 me->run(me->thread_arg);
512 void* return_value = me->run_undetached(me->thread_arg);
513 omni_thread::exit(return_value);
516 // should never get here.
517 #ifndef __BCPLUSPLUS__
524 // Constructors for omni_thread - set up the thread object but don't
528 // construct a detached thread running a given function.
530 omni_thread::omni_thread(void (*fn)(void*), void* arg, priority_t pri)
532 common_constructor(arg, pri, 1);
537 // construct an undetached thread running a given function.
539 omni_thread::omni_thread(void* (*fn)(void*), void* arg, priority_t pri)
541 common_constructor(arg, pri, 0);
546 // construct a thread which will run either run() or run_undetached().
548 omni_thread::omni_thread(void* arg, priority_t pri)
550 common_constructor(arg, pri, 1);
555 // common part of all constructors.
558 omni_thread::common_constructor(void* arg, priority_t pri, int det)
563 next_id_mutex->lock();
565 next_id_mutex->unlock();
568 detached = det; // may be altered in start_undetached()
570 cond_semaphore = CreateSemaphore(NULL, 0, SEMAPHORE_MAX, NULL);
572 if (cond_semaphore == NULL)
573 throw omni_thread_fatal(GetLastError());
575 cond_next = cond_prev = NULL;
576 cond_waiting = FALSE;
587 // Destructor for omni_thread.
590 omni_thread::~omni_thread(void)
592 DB(cerr << "destructor called for thread " << id() << endl);
594 for (key_t i=0; i < _value_alloc; i++) {
601 if (handle && !CloseHandle(handle))
602 throw omni_thread_fatal(GetLastError());
603 if (cond_semaphore && !CloseHandle(cond_semaphore))
604 throw omni_thread_fatal(GetLastError());
613 omni_thread::start(void)
615 omni_mutex_lock l(mutex);
617 if (_state != STATE_NEW)
618 throw omni_thread_invalid();
620 #ifndef __BCPLUSPLUS__
621 // MSVC++ or compatiable
623 handle = (HANDLE)_beginthreadex(
632 throw omni_thread_fatal(GetLastError());
635 handle = (HANDLE)_beginthreadNT(omni_thread_wrapper,
641 if (handle == INVALID_HANDLE_VALUE)
642 throw omni_thread_fatal(errno);
645 if (!SetThreadPriority(handle, nt_priority(_priority)))
646 throw omni_thread_fatal(GetLastError());
648 if (ResumeThread(handle) == 0xffffffff)
649 throw omni_thread_fatal(GetLastError());
651 _state = STATE_RUNNING;
656 // Start a thread which will run the member function run_undetached().
660 omni_thread::start_undetached(void)
662 if ((fn_void != NULL) || (fn_ret != NULL))
663 throw omni_thread_invalid();
671 // join - simply check error conditions & call WaitForSingleObject.
675 omni_thread::join(void** status)
679 if ((_state != STATE_RUNNING) && (_state != STATE_TERMINATED)) {
681 throw omni_thread_invalid();
687 throw omni_thread_invalid();
690 throw omni_thread_invalid();
692 DB(cerr << "omni_thread::join: doing WaitForSingleObject\n");
694 if (WaitForSingleObject(handle, INFINITE) != WAIT_OBJECT_0)
695 throw omni_thread_fatal(GetLastError());
697 DB(cerr << "omni_thread::join: WaitForSingleObject succeeded\n");
700 *status = return_val;
707 // Change this thread's priority.
711 omni_thread::set_priority(priority_t pri)
713 omni_mutex_lock l(mutex);
715 if (_state != STATE_RUNNING)
716 throw omni_thread_invalid();
720 if (!SetThreadPriority(handle, nt_priority(pri)))
721 throw omni_thread_fatal(GetLastError());
726 // create - construct a new thread object and start it running. Returns thread
727 // object if successful, null pointer if not.
733 omni_thread::create(void (*fn)(void*), void* arg, priority_t pri)
735 omni_thread* t = new omni_thread(fn, arg, pri);
740 // undetached version
743 omni_thread::create(void* (*fn)(void*), void* arg, priority_t pri)
745 omni_thread* t = new omni_thread(fn, arg, pri);
752 // exit() _must_ lock the mutex even in the case of a detached thread. This is
753 // because a thread may run to completion before the thread that created it has
754 // had a chance to get out of start(). By locking the mutex we ensure that the
755 // creating thread must have reached the end of start() before we delete the
756 // thread object. Of course, once the call to start() returns, the user can
757 // still incorrectly refer to the thread object, but that's their problem.
761 omni_thread::exit(void* return_value)
763 omni_thread* me = self();
769 me->_state = STATE_TERMINATED;
773 DB(cerr << "omni_thread::exit: thread " << me->id() << " detached "
774 << me->detached << " return value " << return_value << endl);
779 me->return_val = return_value;
784 DB(cerr << "omni_thread::exit: called with a non-omnithread. Exit quietly." << endl);
786 #ifndef __BCPLUSPLUS__
787 // MSVC++ or compatiable
788 // _endthreadex() does not automatically closes the thread handle.
789 // The omni_thread dtor closes the thread handle.
793 // _endthread() does not automatically closes the thread handle.
794 // _endthreadex() is only available if __MFC_COMPAT__ is defined and
795 // all it does is to call _endthread().
802 omni_thread::self(void)
806 me = TlsGetValue(self_tls_index);
809 DB(cerr << "omni_thread::self: called with a non-ominthread. NULL is returned." << endl);
811 return (omni_thread*)me;
816 omni_thread::yield(void)
822 #define MAX_SLEEP_SECONDS (DWORD)4294966 // (2**32-2)/1000
825 omni_thread::sleep(unsigned long secs, unsigned long nanosecs)
827 if (secs <= MAX_SLEEP_SECONDS) {
828 Sleep(secs * 1000 + nanosecs / 1000000);
832 DWORD no_of_max_sleeps = secs / MAX_SLEEP_SECONDS;
834 for (DWORD i = 0; i < no_of_max_sleeps; i++)
835 Sleep(MAX_SLEEP_SECONDS * 1000);
837 Sleep((secs % MAX_SLEEP_SECONDS) * 1000 + nanosecs / 1000000);
842 omni_thread::get_time(unsigned long* abs_sec, unsigned long* abs_nsec,
843 unsigned long rel_sec, unsigned long rel_nsec)
845 get_time_now(abs_sec, abs_nsec);
846 *abs_nsec += rel_nsec;
847 *abs_sec += rel_sec + *abs_nsec / 1000000000;
848 *abs_nsec = *abs_nsec % 1000000000;
853 omni_thread::nt_priority(priority_t pri)
858 return THREAD_PRIORITY_LOWEST;
860 case PRIORITY_NORMAL:
861 return THREAD_PRIORITY_NORMAL;
864 return THREAD_PRIORITY_HIGHEST;
867 throw omni_thread_invalid();
868 return 0; /* keep msvc++ happy */
873 get_time_now(unsigned long* abs_sec, unsigned long* abs_nsec)
875 static int days_in_preceding_months[12]
876 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
877 static int days_in_preceding_months_leap[12]
878 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };
883 *abs_nsec = st.wMilliseconds * 1000000;
885 // this formula should work until 1st March 2100
887 DWORD days = ((st.wYear - 1970) * 365 + (st.wYear - 1969) / 4
889 ? days_in_preceding_months[st.wMonth - 1]
890 : days_in_preceding_months_leap[st.wMonth - 1])
893 *abs_sec = st.wSecond + 60 * (st.wMinute + 60 * (st.wHour + 24 * days));
897 omni_thread::stacksize(unsigned long sz)
903 omni_thread::stacksize()
912 class omni_thread_dummy : public omni_thread {
914 inline omni_thread_dummy() : omni_thread()
917 _state = STATE_RUNNING;
919 if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
920 GetCurrentProcess(), &handle,
921 0, FALSE, DUPLICATE_SAME_ACCESS))
922 throw omni_thread_fatal(GetLastError());
924 nt_id = GetCurrentThreadId();
926 if (!TlsSetValue(self_tls_index, (LPVOID)this))
927 throw omni_thread_fatal(GetLastError());
929 inline ~omni_thread_dummy()
931 if (!TlsSetValue(self_tls_index, (LPVOID)0))
932 throw omni_thread_fatal(GetLastError());
937 omni_thread::create_dummy()
939 if (omni_thread::self())
940 throw omni_thread_invalid();
942 return new omni_thread_dummy;
946 omni_thread::release_dummy()
948 omni_thread* self = omni_thread::self();
949 if (!self || !self->_dummy)
950 throw omni_thread_invalid();
952 omni_thread_dummy* dummy = (omni_thread_dummy*)self;
957 #if defined(__DMC__) && defined(_WINDLL)
958 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
965 #define INSIDE_THREAD_IMPL_CC
966 #include "threaddata.cc"
967 #undef INSIDE_THREAD_IMPL_CC