2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
11 * This file contains a skeleton pthread implementation for NT.
12 * This is not intended to be a fully compliant pthread implementation
13 * The purpose of this file is to only implement those functions that
14 * are truly needed to support the afs code base.
16 * A secondary goal is to allow a "real" pthread implementation to
17 * replace this file without any modification to code that depends upon
20 * The function signatures and argument types are meant to be the same
21 * as their UNIX prototypes.
22 * Where possible, the POSIX specified return values are used.
23 * For situations where an error can occur, but no corresponding
24 * POSIX error value exists, unique (within a given function) negative
25 * numbers are used for errors to avoid collsions with the errno
29 #include <afs/param.h>
37 #include <sys/timeb.h>
39 #define PTHREAD_EXIT_EXCEPTION 0x1
42 * Posix threads uses static initialization for pthread_once control
43 * objects, and under NT, every sophisticated synchronization primitive
44 * uses procedural initialization. This forces the use of CompareExchange
45 * (aka test and set) and busy waiting for threads that compete to run
46 * a pthread_once'd function. We make these "busy" threads give up their
47 * timeslice - which should cause acceptable behavior on a single processor
48 * machine, but on a multiprocessor machine this could very well result
52 int pthread_once(pthread_once_t *once_control, void (*init_routine)(void)) {
55 if ((once_control != NULL) && (init_routine != NULL)) {
56 if (InterlockedExchange((LPLONG)&once_control->call_started,
59 once_control->call_running = 0;
61 /* use Sleep() since SwitchToThread() not available on Win95 */
62 while(once_control->call_running) Sleep(20);
71 * For now only support PTHREAD_PROCESS_PRIVATE mutexes.
72 * if PTHREAD_PROCESS_SHARED are required later they can be added
75 int pthread_mutex_init(pthread_mutex_t *mp, const pthread_mutexattr_t *attr) {
78 if ((mp != NULL) && (attr == NULL)) {
79 InitializeCriticalSection(&mp->cs);
89 * Under NT, critical sections can be locked recursively by the owning
90 * thread. This is opposite of the pthread spec, and so we keep track
91 * of the thread that has locked a critical section. If the same thread
92 * tries to lock a critical section more than once we fail.
94 int pthread_mutex_trylock(pthread_mutex_t *mp) {
98 /* TryEnterCriticalSection() not available on Win95, so just wait for
99 * the lock. Correct code generally can't depend on how long the
100 * function takes to return, so the only code that will be broken is
101 * that for which 1) the mutex *mp is obtained and never released or
102 * 2) the mutex *mp is intentionally held until trylock() returns.
103 * These cases are unusual and don't appear in normal (non-test) AFS
104 * code; furthermore, we can reduce (but not eliminate!) the problem by
105 * sneaking a look at isLocked even though we don't hold the
106 * CRITICAL_SECTION in mutex *mp and are thus vulnerable to race
107 * conditions. Note that self-deadlock isn't a problem since
108 * CRITICAL_SECTION objects are recursive.
110 * Given the very restricted usage of the pthread library on Windows 95,
111 * we can live with these limitations.
117 rc = pthread_mutex_lock(mp);
123 /* TryEnterCriticalSection() provided on other MS platforms of interest */
125 if (TryEnterCriticalSection(&mp->cs)) {
127 /* same thread tried to recursively lock, fail */
128 LeaveCriticalSection(&mp->cs);
132 mp->tid = GetCurrentThreadId();
141 #endif /* AFS_WIN95_ENV */
147 int pthread_mutex_lock(pthread_mutex_t *mp) {
151 EnterCriticalSection(&mp->cs);
154 mp->tid = GetCurrentThreadId();
157 * same thread tried to recursively lock this mutex.
158 * Under real POSIX, this would cause a deadlock, but NT only
159 * supports recursive mutexes so we indicate the situation
160 * by returning EDEADLK.
162 LeaveCriticalSection(&mp->cs);
172 int pthread_mutex_unlock(pthread_mutex_t *mp) {
176 if (mp->tid == GetCurrentThreadId()) {
179 LeaveCriticalSection(&mp->cs);
189 int pthread_mutex_destroy(pthread_mutex_t *mp) {
193 DeleteCriticalSection(&mp->cs);
202 * keys is used to keep track of which keys are currently
203 * in use by the threads library. pthread_tsd_mutex is used
206 * The bookkeeping for keys in use and destructor function/key is
207 * at the library level. Each individual thread only keeps its
208 * per key data value. This implies that the keys array and the
209 * tsd array in the pthread_t structure need to always be exactly
210 * the same size since the same index is used for both arrays.
215 void (*destructor)(void *);
216 } pthread_tsd_table_t;
218 static pthread_tsd_table_t keys[PTHREAD_KEYS_MAX];
219 static pthread_mutex_t pthread_tsd_mutex;
220 static pthread_once_t pthread_tsd_once = PTHREAD_ONCE_INIT;
223 * In order to support p_self() and p_join() under NT,
224 * we have to keep our own list of active threads and provide a mapping
225 * function that maps the NT thread id to our internal structure.
226 * The main reason that this is necessary is that GetCurrentThread
227 * returns a special constant not an actual handle to the thread.
228 * This makes it impossible to write a p_self() function that works
229 * with only the native NT functions.
232 static struct rx_queue active_Q;
233 static struct rx_queue cache_Q;
235 static pthread_mutex_t active_Q_mutex;
236 static pthread_mutex_t cache_Q_mutex;
238 static pthread_once_t pthread_cache_once = PTHREAD_ONCE_INIT;
239 static int pthread_cache_done;
241 typedef struct thread {
242 struct rx_queue thread_queue;
245 pthread_cond_t wait_terminate;
253 } thread_t, *thread_p;
255 static void create_once(void) {
256 queue_Init(&active_Q);
257 queue_Init(&cache_Q);
258 pthread_mutex_init(&active_Q_mutex, (const pthread_mutexattr_t*)0);
259 pthread_mutex_init(&cache_Q_mutex, (const pthread_mutexattr_t*)0);
260 pthread_cache_done = 1;
263 static void put_thread(thread_p old) {
265 CloseHandle(old->t_handle);
266 pthread_mutex_lock(&cache_Q_mutex);
267 queue_Prepend(&cache_Q, old);
268 pthread_mutex_unlock(&cache_Q_mutex);
271 static thread_p get_thread() {
274 pthread_mutex_lock(&cache_Q_mutex);
276 if (queue_IsEmpty(&cache_Q)) {
277 new = (thread_p) malloc(sizeof(thread_t));
280 * One time initialization - we assume threads put back have
281 * unlocked mutexes and condition variables with no waiters
283 * These functions cannot fail currently.
285 pthread_cond_init(&new->wait_terminate,(const pthread_condattr_t *)0);
288 new = queue_First(&cache_Q, thread);
292 pthread_mutex_unlock(&cache_Q_mutex);
295 * Initialization done every time we hand out a thread_t
301 new->waiter_count = 0;
302 new->has_been_joined = 0;
309 * The thread start function signature is different on NT than the pthread
310 * spec so we create a tiny stub to map from one signature to the next.
311 * This assumes that a void * can be stored within a DWORD.
315 void *(*func)(void *);
317 char *tsd[PTHREAD_KEYS_MAX];
321 static DWORD tsd_index = 0xffffffff;
322 static DWORD tsd_pthread_index = 0xffffffff;
323 static pthread_once_t global_tsd_once = PTHREAD_ONCE_INIT;
326 static void tsd_once(void) {
327 while(tsd_index == 0xffffffff) {
328 tsd_index = TlsAlloc();
330 while(tsd_pthread_index == 0xffffffff) {
331 tsd_pthread_index = TlsAlloc();
336 static void tsd_free_all(char *tsd[PTHREAD_KEYS_MAX]) {
337 int call_more_destructors = 0;
341 void (*destructor)(void *);
342 call_more_destructors = 0;
343 for(i=0;i<PTHREAD_KEYS_MAX;i++) {
344 if (tsd[i] != NULL) {
345 destructor = keys[i].destructor;
346 value = (void *)tsd[i];
348 if (destructor != NULL) {
351 * A side-effect of calling a destructor function is that
352 * more thread specific may be created for this thread.
353 * If we call a destructor, we must recycle through the
354 * entire list again and run any new destructors.
356 call_more_destructors = 1;
360 } while(call_more_destructors);
363 static DWORD WINAPI afs_pthread_create_stub(LPVOID param) {
364 pthread_create_t *t = (pthread_create_t *) param;
368 * Initialize thread specific storage structures.
371 memset(t->tsd, 0, (sizeof(char *) * PTHREAD_KEYS_MAX));
372 (tsd_done || pthread_once(&global_tsd_once, tsd_once));
373 TlsSetValue(tsd_index, (LPVOID) (t->tsd));
374 TlsSetValue(tsd_pthread_index, (LPVOID) (t->me));
377 * Call the function the user passed to pthread_create and catch the
378 * pthread exit exception if it is raised.
382 rc = (*(t->func))(t->arg);
383 } __except(GetExceptionCode() == PTHREAD_EXIT_EXCEPTION) {
384 rc = t->me->rc; /* rc is set at pthread_exit */
388 * Cycle through the thread specific data for this thread and
389 * call the destructor function for each non-NULL datum
392 tsd_free_all (t->tsd);
396 * If we are joinable, signal any waiters.
399 pthread_mutex_lock(&active_Q_mutex);
400 if (t->me->is_joinable) {
403 if (t->me->waiter_count) {
404 pthread_cond_broadcast(&t->me->wait_terminate);
410 pthread_mutex_unlock(&active_Q_mutex);
417 * If a pthread function is called on a thread which was not created by
418 * pthread_create(), that thread will have an entry added to the active_Q
419 * by pthread_self(). When the thread terminates, we need to know
420 * about it, so that we can perform cleanup. A dedicated thread is therefore
421 * maintained, which watches for any thread marked "native_thread==1"
422 * in the active_Q to terminate. The thread spends most of its time sleeping:
423 * it can be signalled by a dedicated event in order to alert it to the
424 * presense of a new thread to watch, or will wake up automatically when
425 * a native thread terminates.
428 static DWORD terminate_thread_id = 0;
429 static HANDLE terminate_thread_handle = INVALID_HANDLE_VALUE;
430 static HANDLE terminate_thread_wakeup_event = INVALID_HANDLE_VALUE;
431 static HANDLE *terminate_thread_wakeup_list = NULL;
432 static size_t terminate_thread_wakeup_list_size = 0;
434 static DWORD WINAPI terminate_thread_routine(LPVOID param) {
436 size_t native_thread_count;
437 int should_terminate;
438 int terminate_thread_wakeup_list_index;
442 * Grab the active_Q_mutex, and while we hold it, scan the active_Q
443 * to see how many native threads we need to watch. If we don't need
444 * to watch any, we can stop this watcher thread entirely (or not);
445 * if we do need to watch some, fill the terminate_thread_wakeup_list
446 * array and go to sleep.
450 native_thread_count = 0;
451 should_terminate = FALSE;
452 pthread_mutex_lock(&active_Q_mutex);
454 for(queue_Scan(&active_Q, cur, next, thread)) {
455 if (cur->native_thread)
456 ++native_thread_count;
460 * At this point we could decide to terminate this watcher thread
461 * whenever there are no longer any native threads to watch--however,
462 * since thread creation is a time-consuming thing, and since this
463 * thread spends all its time sleeping anyway, there's no real
464 * compelling reason to do so. Thus, the following statement is
467 * if (!native_thread_count) {
468 * should_terminate = TRUE;
471 * Restore the snippet above to cause this watcher thread to only
472 * live whenever there are native threads to watch.
477 * Make sure that our wakeup_list array is large enough to contain
478 * the handles of all the native threads /and/ to contain an
479 * entry for our wakeup_event (in case another native thread comes
482 if (terminate_thread_wakeup_list_size < (1+native_thread_count)) {
483 if (terminate_thread_wakeup_list)
484 free (terminate_thread_wakeup_list);
485 terminate_thread_wakeup_list = (HANDLE*)malloc (sizeof(HANDLE) *
486 (1+native_thread_count));
487 if (terminate_thread_wakeup_list == NULL) {
488 should_terminate = TRUE;
490 terminate_thread_wakeup_list_size = 1+native_thread_count;
494 if (should_terminate) {
496 * Here, we've decided to terminate this watcher thread.
497 * Free our wakeup event and wakeup list, then release the
498 * active_Q_mutex and break this loop.
500 if (terminate_thread_wakeup_list)
501 free (terminate_thread_wakeup_list);
502 CloseHandle (terminate_thread_wakeup_event);
503 terminate_thread_id = 0;
504 terminate_thread_handle = INVALID_HANDLE_VALUE;
505 terminate_thread_wakeup_event = INVALID_HANDLE_VALUE;
506 terminate_thread_wakeup_list = NULL;
507 terminate_thread_wakeup_list_size = 0;
508 pthread_mutex_unlock(&active_Q_mutex);
512 * Here, we've decided to wait for native threads et al.
513 * Fill out the wakeup_list.
515 memset(terminate_thread_wakeup_list, 0x00, (sizeof(HANDLE) *
516 (1+native_thread_count)));
518 terminate_thread_wakeup_list[0] = terminate_thread_wakeup_event;
519 terminate_thread_wakeup_list_index = 1;
523 for(queue_Scan(&active_Q, cur, next, thread)) {
524 if (cur->native_thread) {
525 terminate_thread_wakeup_list[terminate_thread_wakeup_list_index]
527 ++terminate_thread_wakeup_list_index;
531 ResetEvent (terminate_thread_wakeup_event);
534 pthread_mutex_unlock(&active_Q_mutex);
537 * Time to sleep. We'll wake up if either of the following happen:
538 * 1) Someone sets the terminate_thread_wakeup_event (this will
539 * happen if another native thread gets added to the active_Q)
540 * 2) One or more of the native threads terminate
542 terminate_thread_wakeup_list_index = WaitForMultipleObjects(
543 1+native_thread_count,
544 terminate_thread_wakeup_list,
549 * If we awoke from sleep because an event other than
550 * terminate_thread_wakeup_event was triggered, it means the
551 * specified thread has terminated. (If more than one thread
552 * terminated, we'll handle this first one and loop around--
553 * the event's handle will still be triggered, so we just won't
554 * block at all when we sleep next time around.)
556 if (terminate_thread_wakeup_list_index > 0) {
557 pthread_mutex_lock(&active_Q_mutex);
561 for(queue_Scan(&active_Q, cur, next, thread)) {
562 if (cur->t_handle == terminate_thread_wakeup_list[ terminate_thread_wakeup_list_index ])
568 * Cycle through the thread specific data for the specified
569 * thread and call the destructor function for each non-NULL
570 * datum. Then remove the thread_t from active_Q and put it
571 * back on cache_Q for possible later re-use.
573 if(cur->tsd != NULL) {
574 tsd_free_all(cur->tsd);
582 pthread_mutex_unlock(&active_Q_mutex);
589 static void pthread_sync_terminate_thread(void) {
590 (pthread_cache_done || pthread_once(&pthread_cache_once, create_once));
592 if (terminate_thread_handle == INVALID_HANDLE_VALUE) {
593 terminate_thread_wakeup_event = CreateEvent((LPSECURITY_ATTRIBUTES) 0,
594 TRUE, FALSE, (LPCTSTR) 0);
595 terminate_thread_handle = CreateThread((LPSECURITY_ATTRIBUTES) 0, 0,
596 terminate_thread_routine, (LPVOID) 0, 0,
597 &terminate_thread_id);
599 SetEvent (terminate_thread_wakeup_event);
605 * Only support the detached attribute specifier for pthread_create.
606 * Under NT, thread stacks grow automatically as needed.
609 int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void *(*func)(void *), void *arg) {
611 pthread_create_t *t = NULL;
613 (pthread_cache_done || pthread_once(&pthread_cache_once, create_once));
615 if ((tid != NULL) && (func != NULL)) {
616 if ((t = (pthread_create_t *) malloc(sizeof(pthread_create_t))) &&
617 (t->me = get_thread()) ) {
620 *tid = (pthread_t) t->me;
622 t->me->is_joinable = attr->is_joinable;
624 t->me->is_joinable = PTHREAD_CREATE_JOINABLE;
626 t->me->native_thread = 0;
629 * At the point (before we actually create the thread)
630 * we need to add our entry to the active queue. This ensures
631 * us that other threads who may run after this thread returns
632 * will find an entry for the create thread regardless of
633 * whether the newly created thread has run or not.
634 * In the event the thread create fails, we will have temporarily
635 * added an entry to the list that was never valid, but we
636 * (i.e. the thread that is calling thread_create) are the
637 * only one who could possibly know about the bogus entry
638 * since we hold the active_Q_mutex.
640 pthread_mutex_lock(&active_Q_mutex);
641 queue_Prepend(&active_Q, t->me);
642 t->me->t_handle = CreateThread((LPSECURITY_ATTRIBUTES) 0, 0,
643 afs_pthread_create_stub, (LPVOID) t, 0,
645 if (t->me->t_handle == 0) {
647 * we only free t if the thread wasn't created, otherwise
648 * it's free'd by the new thread.
655 pthread_mutex_unlock(&active_Q_mutex);
668 int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr) {
672 * Only support default attribute -> must pass a NULL pointer for
675 if ((attr == NULL) && (cond != NULL)) {
676 InitializeCriticalSection(&cond->cs);
677 queue_Init(&cond->waiting_threads);
686 * In order to optimize the performance of condition variables,
687 * we maintain a pool of cond_waiter_t's that have been dynamically
688 * allocated. There is no attempt made to garbage collect these -
689 * once they have been created, they stay in the cache for the life
693 static struct rx_queue waiter_cache;
694 static CRITICAL_SECTION waiter_cache_cs;
695 static int waiter_cache_init;
696 static pthread_once_t waiter_cache_once = PTHREAD_ONCE_INIT;
698 static void init_waiter_cache(void) {
699 InitializeCriticalSection(&waiter_cache_cs);
700 waiter_cache_init = 1;
701 queue_Init(&waiter_cache);
704 static cond_waiters_t *get_waiter() {
705 cond_waiters_t *new = NULL;
707 (waiter_cache_init || pthread_once(&waiter_cache_once, init_waiter_cache));
709 EnterCriticalSection(&waiter_cache_cs);
711 if (queue_IsEmpty(&waiter_cache)) {
712 new = (cond_waiters_t *) malloc(sizeof(cond_waiters_t));
715 CHAR eventName[MAX_PATH];
716 static eventCount = 0;
717 sprintf(eventName, "cond_waiters_t %d::%d", _getpid(), eventCount++);
718 new->event = CreateEvent((LPSECURITY_ATTRIBUTES) 0, FALSE,
719 FALSE, (LPCTSTR) eventName);
721 new->event = CreateEvent((LPSECURITY_ATTRIBUTES) 0, FALSE,
723 if (new->event == NULL) {
730 new = queue_First(&waiter_cache, cond_waiter);
734 LeaveCriticalSection(&waiter_cache_cs);
738 static void put_waiter(cond_waiters_t *old) {
740 (waiter_cache_init || pthread_once(&waiter_cache_once, init_waiter_cache));
742 EnterCriticalSection(&waiter_cache_cs);
743 queue_Prepend(&waiter_cache, old);
744 LeaveCriticalSection(&waiter_cache_cs);
747 static int cond_wait_internal(pthread_cond_t *cond, pthread_mutex_t *mutex, const DWORD time) {
749 cond_waiters_t *my_entry = get_waiter();
750 cond_waiters_t *cur, *next;
751 int hasnt_been_signalled=0;
753 if ((cond != NULL) && (mutex != NULL) && (my_entry != NULL)) {
754 EnterCriticalSection(&cond->cs);
755 queue_Append(&cond->waiting_threads, my_entry);
756 LeaveCriticalSection(&cond->cs);
758 if (!pthread_mutex_unlock(mutex)) {
759 switch(WaitForSingleObject(my_entry->event, time)) {
766 * This is a royal pain. We've timed out waiting
767 * for the signal, but between the time out and here
768 * it is possible that we were actually signalled by
769 * another thread. So we grab the condition lock
770 * and scan the waiting thread queue to see if we are
771 * still there. If we are, we just remove ourselves.
773 * If we are no longer listed in the waiter queue,
774 * it means that we were signalled after the time
775 * out occurred and so we have to do another wait
776 * WHICH HAS TO SUCCEED! In this case, we reset
777 * rc to indicate that we were signalled.
779 * We have to wait or otherwise, the event
780 * would be cached in the signalled state, which
781 * is wrong. It might be more efficient to just
782 * close and reopen the event.
784 EnterCriticalSection(&cond->cs);
785 for(queue_Scan(&cond->waiting_threads, cur,
786 next, cond_waiter)) {
787 if (cur == my_entry) {
788 hasnt_been_signalled = 1;
792 if (hasnt_been_signalled) {
796 if (ResetEvent(my_entry->event)) {
797 if (pthread_mutex_lock(mutex)) {
804 LeaveCriticalSection(&cond->cs);
810 if (pthread_mutex_lock(mutex)) {
825 if (my_entry != NULL) {
826 put_waiter(my_entry);
832 int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) {
835 rc = cond_wait_internal(cond, mutex, INFINITE);
839 int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime) {
841 struct _timeb now, then;
842 short n_milli, t_milli;
844 if (abstime->tv_nsec < 1000000000) {
847 * pthread timedwait uses an absolute time, NT uses relative so
848 * we convert here. The millitm field in the timeb struct is
849 * unsigned, but we need to do subtraction preserving the sign,
850 * so we copy the fields into temporary variables.
853 * In NT 4.0 SP3, WaitForSingleObject can occassionally timeout
854 * earlier than requested. Therefore, our pthread_cond_timedwait
855 * can also return early.
859 n_milli = now.millitm;
860 then.time = abstime->tv_sec;
861 t_milli = abstime->tv_nsec/1000000;
863 if((then.time > now.time ||
864 (then.time == now.time && t_milli > n_milli))) {
865 if((t_milli -= n_milli) < 0) {
869 then.time -= now.time;
871 if ((then.time + (clock() / CLOCKS_PER_SEC)) <= 50000000) {
873 * Under NT, we can only wait for milliseconds, so we
874 * round up the wait time here.
876 rc = cond_wait_internal(cond, mutex,
877 ((then.time * 1000) + (t_milli)));
891 int pthread_cond_signal(pthread_cond_t *cond) {
893 cond_waiters_t *release_thread;
896 EnterCriticalSection(&cond->cs);
899 * remove the first waiting thread from the queue
900 * and resume his execution
902 if (queue_IsNotEmpty(&cond->waiting_threads)) {
903 release_thread = queue_First(&cond->waiting_threads,
905 queue_Remove(release_thread);
906 if (!SetEvent(release_thread->event)) {
911 LeaveCriticalSection(&cond->cs);
919 int pthread_cond_broadcast(pthread_cond_t *cond) {
921 cond_waiters_t *release_thread, *next_thread;
924 EnterCriticalSection(&cond->cs);
927 * Empty the waiting_threads queue.
929 if (queue_IsNotEmpty(&cond->waiting_threads)) {
930 for(queue_Scan(&cond->waiting_threads, release_thread,
931 next_thread, cond_waiter)) {
932 queue_Remove(release_thread);
933 if (!SetEvent(release_thread->event)) {
939 LeaveCriticalSection(&cond->cs);
947 int pthread_cond_destroy(pthread_cond_t *cond) {
951 DeleteCriticalSection(&cond->cs);
957 * A previous version of this file had code to check the waiter
958 * queue and empty it here. This has been removed in the hopes
959 * that it will aid in debugging.
965 int pthread_join(pthread_t target_thread, void **status) {
970 target = (thread_p) target_thread;
971 me = (thread_p) pthread_self();
975 * Check to see that the target thread is joinable and hasn't
976 * already been joined.
979 pthread_mutex_lock(&active_Q_mutex);
981 for(queue_Scan(&active_Q, cur, next, thread)) {
982 if (target == cur) break;
986 if ((!target->is_joinable) || (target->has_been_joined)) {
994 pthread_mutex_unlock(&active_Q_mutex);
998 target->waiter_count++;
999 while(target->running) {
1000 pthread_cond_wait(&target->wait_terminate, &active_Q_mutex);
1004 * Only one waiter gets the status and is allowed to join, all the
1005 * others get an error.
1008 if (target->has_been_joined) {
1011 target->has_been_joined = 1;
1013 *status = target->rc;
1018 * If we're the last waiter it is our responsibility to remove
1019 * this entry from the terminated list and put it back in the
1023 target->waiter_count--;
1024 if (target->waiter_count == 0) {
1025 queue_Remove(target);
1026 pthread_mutex_unlock(&active_Q_mutex);
1029 pthread_mutex_unlock(&active_Q_mutex);
1039 * Note that we can't return an error from pthread_getspecific so
1040 * we return a NULL pointer instead.
1043 void *pthread_getspecific(pthread_key_t key) {
1045 char **tsd = TlsGetValue(tsd_index);
1047 if ((key > -1) && (key < PTHREAD_KEYS_MAX )) {
1048 rc = (void *) *(tsd + key);
1054 static int p_tsd_done;
1056 static void pthread_tsd_init(void) {
1057 pthread_mutex_init(&pthread_tsd_mutex, (const pthread_mutexattr_t*)0);
1061 int pthread_key_create(pthread_key_t *keyp, void (*destructor)(void *value)) {
1065 if (p_tsd_done || (!pthread_once(&pthread_tsd_once, pthread_tsd_init))) {
1066 if (!pthread_mutex_lock(&pthread_tsd_mutex)) {
1067 for(i=0;i<PTHREAD_KEYS_MAX;i++) {
1068 if (!keys[i].inuse) break;
1071 if (!keys[i].inuse) {
1073 keys[i].destructor = destructor;
1078 pthread_mutex_unlock(&pthread_tsd_mutex);
1089 int pthread_key_delete(pthread_key_t key) {
1092 if (p_tsd_done || (!pthread_once(&pthread_tsd_once, pthread_tsd_init))) {
1093 if ((key > -1) && (key < PTHREAD_KEYS_MAX )) {
1094 if (!pthread_mutex_lock(&pthread_tsd_mutex)) {
1095 keys[key].inuse = 0;
1096 keys[key].destructor = NULL;
1097 pthread_mutex_unlock(&pthread_tsd_mutex);
1111 int pthread_setspecific(pthread_key_t key, const void *value) {
1115 if (p_tsd_done || (!pthread_once(&pthread_tsd_once, pthread_tsd_init))) {
1116 if ((key > -1) && (key < PTHREAD_KEYS_MAX )) {
1117 if (!pthread_mutex_lock(&pthread_tsd_mutex)) {
1118 if (keys[key].inuse) {
1119 tsd = TlsGetValue(tsd_index);
1120 *(tsd + key) = (char *) value;
1124 pthread_mutex_unlock(&pthread_tsd_mutex);
1138 pthread_t pthread_self(void) {
1140 DWORD my_id = GetCurrentThreadId();
1142 (pthread_cache_done || pthread_once(&pthread_cache_once, create_once));
1143 (tsd_done || pthread_once(&global_tsd_once, tsd_once));
1145 pthread_mutex_lock(&active_Q_mutex);
1147 cur = TlsGetValue (tsd_pthread_index);
1151 * This thread's ID was not found in our list of pthread-API client
1152 * threads (e.g., those threads created via pthread_create). Create
1155 if ((cur = get_thread()) != NULL) {
1156 cur->is_joinable = 0;
1158 cur->native_thread = 1;
1159 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
1160 GetCurrentProcess(), &cur->t_handle, 0,
1161 TRUE, DUPLICATE_SAME_ACCESS);
1164 * We'll also need a place to store key data for this thread
1166 if ((cur->tsd = malloc(sizeof(char*) * PTHREAD_KEYS_MAX)) != NULL) {
1167 memset(cur->tsd, 0, (sizeof(char*) * PTHREAD_KEYS_MAX));
1169 TlsSetValue(tsd_index, (LPVOID)cur->tsd);
1170 TlsSetValue(tsd_pthread_index, (LPVOID)cur);
1173 * The thread_t structure is complete; add it to the active_Q
1175 queue_Prepend(&active_Q, cur);
1178 * We were able to successfully insert a new entry into the
1179 * active_Q; however, when this thread terminates, we will need
1180 * to know about it. The pthread_sync_terminate_thread() routine
1181 * will make sure there is a dedicated thread waiting for any
1182 * native-thread entries in the active_Q to terminate.
1184 pthread_sync_terminate_thread();
1188 pthread_mutex_unlock(&active_Q_mutex);
1190 return (void *) cur;
1193 int pthread_equal(pthread_t t1, pthread_t t2) {
1197 int pthread_attr_destroy(pthread_attr_t *attr) {
1203 int pthread_attr_init(pthread_attr_t *attr) {
1207 attr->is_joinable = PTHREAD_CREATE_JOINABLE;
1215 int pthread_attr_getdetachstate(pthread_attr_t *attr, int *detachstate) {
1218 if ((attr != NULL) && (detachstate != NULL)) {
1219 *detachstate = attr->is_joinable;
1226 int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate) {
1229 if ((attr != NULL) && ((detachstate == PTHREAD_CREATE_JOINABLE) ||
1230 (detachstate == PTHREAD_CREATE_DETACHED))) {
1231 attr->is_joinable = detachstate;
1238 void pthread_exit(void *status) {
1239 thread_p me = (thread_p) pthread_self();
1242 * Support pthread_exit for thread's created by calling pthread_create
1243 * only. Do this by using an exception that will transfer control
1244 * back to afs_pthread_create_stub. Store away our status before
1247 * If this turns out to be a native thread, the exception will be
1248 * unhandled and the process will terminate.
1252 RaiseException(PTHREAD_EXIT_EXCEPTION, 0, 0, NULL);