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 CHAR eventName[MAX_PATH];
594 static eventCount = 0;
595 sprintf(eventName, "terminate_thread_wakeup_event %d::%d", _getpid(), eventCount++);
596 terminate_thread_wakeup_event = CreateEvent((LPSECURITY_ATTRIBUTES) 0,
597 TRUE, FALSE, (LPCTSTR) eventName);
598 terminate_thread_handle = CreateThread((LPSECURITY_ATTRIBUTES) 0, 0,
599 terminate_thread_routine, (LPVOID) 0, 0,
600 &terminate_thread_id);
602 SetEvent (terminate_thread_wakeup_event);
608 * Only support the detached attribute specifier for pthread_create.
609 * Under NT, thread stacks grow automatically as needed.
612 int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void *(*func)(void *), void *arg) {
614 pthread_create_t *t = NULL;
616 (pthread_cache_done || pthread_once(&pthread_cache_once, create_once));
618 if ((tid != NULL) && (func != NULL)) {
619 if ((t = (pthread_create_t *) malloc(sizeof(pthread_create_t))) &&
620 (t->me = get_thread()) ) {
623 *tid = (pthread_t) t->me;
625 t->me->is_joinable = attr->is_joinable;
627 t->me->is_joinable = PTHREAD_CREATE_JOINABLE;
629 t->me->native_thread = 0;
632 * At the point (before we actually create the thread)
633 * we need to add our entry to the active queue. This ensures
634 * us that other threads who may run after this thread returns
635 * will find an entry for the create thread regardless of
636 * whether the newly created thread has run or not.
637 * In the event the thread create fails, we will have temporarily
638 * added an entry to the list that was never valid, but we
639 * (i.e. the thread that is calling thread_create) are the
640 * only one who could possibly know about the bogus entry
641 * since we hold the active_Q_mutex.
643 pthread_mutex_lock(&active_Q_mutex);
644 queue_Prepend(&active_Q, t->me);
645 t->me->t_handle = CreateThread((LPSECURITY_ATTRIBUTES) 0, 0,
646 afs_pthread_create_stub, (LPVOID) t, 0,
648 if (t->me->t_handle == 0) {
650 * we only free t if the thread wasn't created, otherwise
651 * it's free'd by the new thread.
658 pthread_mutex_unlock(&active_Q_mutex);
671 int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr) {
675 * Only support default attribute -> must pass a NULL pointer for
678 if ((attr == NULL) && (cond != NULL)) {
679 InitializeCriticalSection(&cond->cs);
680 queue_Init(&cond->waiting_threads);
689 * In order to optimize the performance of condition variables,
690 * we maintain a pool of cond_waiter_t's that have been dynamically
691 * allocated. There is no attempt made to garbage collect these -
692 * once they have been created, they stay in the cache for the life
696 static struct rx_queue waiter_cache;
697 static CRITICAL_SECTION waiter_cache_cs;
698 static int waiter_cache_init;
699 static pthread_once_t waiter_cache_once = PTHREAD_ONCE_INIT;
701 static void init_waiter_cache(void) {
702 InitializeCriticalSection(&waiter_cache_cs);
703 waiter_cache_init = 1;
704 queue_Init(&waiter_cache);
707 static cond_waiters_t *get_waiter() {
708 cond_waiters_t *new = NULL;
710 (waiter_cache_init || pthread_once(&waiter_cache_once, init_waiter_cache));
712 EnterCriticalSection(&waiter_cache_cs);
714 if (queue_IsEmpty(&waiter_cache)) {
715 new = (cond_waiters_t *) malloc(sizeof(cond_waiters_t));
717 CHAR eventName[MAX_PATH];
718 static eventCount = 0;
719 sprintf(eventName, "cond_waiters_t %d::%d", _getpid(), eventCount++);
720 new->event = CreateEvent((LPSECURITY_ATTRIBUTES) 0, FALSE,
721 FALSE, (LPCTSTR) eventName);
722 if (new->event == NULL) {
728 new = queue_First(&waiter_cache, cond_waiter);
732 LeaveCriticalSection(&waiter_cache_cs);
737 static void put_waiter(cond_waiters_t *old) {
739 (waiter_cache_init || pthread_once(&waiter_cache_once, init_waiter_cache));
741 EnterCriticalSection(&waiter_cache_cs);
742 queue_Prepend(&waiter_cache, old);
743 LeaveCriticalSection(&waiter_cache_cs);
746 static int cond_wait_internal(pthread_cond_t *cond, pthread_mutex_t *mutex, const DWORD time) {
748 cond_waiters_t *my_entry = get_waiter();
749 cond_waiters_t *cur, *next;
750 int hasnt_been_signalled=0;
752 if ((cond != NULL) && (mutex != NULL) && (my_entry != NULL)) {
753 EnterCriticalSection(&cond->cs);
754 queue_Append(&cond->waiting_threads, my_entry);
755 LeaveCriticalSection(&cond->cs);
757 if (!pthread_mutex_unlock(mutex)) {
758 switch(WaitForSingleObject(my_entry->event, time)) {
765 * This is a royal pain. We've timed out waiting
766 * for the signal, but between the time out and here
767 * it is possible that we were actually signalled by
768 * another thread. So we grab the condition lock
769 * and scan the waiting thread queue to see if we are
770 * still there. If we are, we just remove ourselves.
772 * If we are no longer listed in the waiter queue,
773 * it means that we were signalled after the time
774 * out occurred and so we have to do another wait
775 * WHICH HAS TO SUCCEED! In this case, we reset
776 * rc to indicate that we were signalled.
778 * We have to wait or otherwise, the event
779 * would be cached in the signalled state, which
780 * is wrong. It might be more efficient to just
781 * close and reopen the event.
783 EnterCriticalSection(&cond->cs);
784 for(queue_Scan(&cond->waiting_threads, cur,
785 next, cond_waiter)) {
786 if (cur == my_entry) {
787 hasnt_been_signalled = 1;
791 if (hasnt_been_signalled) {
795 if (ResetEvent(my_entry->event)) {
796 if (pthread_mutex_lock(mutex)) {
803 LeaveCriticalSection(&cond->cs);
809 if (pthread_mutex_lock(mutex)) {
824 if (my_entry != NULL) {
825 put_waiter(my_entry);
831 int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) {
834 rc = cond_wait_internal(cond, mutex, INFINITE);
838 int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime) {
840 struct _timeb now, then;
841 short n_milli, t_milli;
843 if (abstime->tv_nsec < 1000000000) {
846 * pthread timedwait uses an absolute time, NT uses relative so
847 * we convert here. The millitm field in the timeb struct is
848 * unsigned, but we need to do subtraction preserving the sign,
849 * so we copy the fields into temporary variables.
852 * In NT 4.0 SP3, WaitForSingleObject can occassionally timeout
853 * earlier than requested. Therefore, our pthread_cond_timedwait
854 * can also return early.
858 n_milli = now.millitm;
859 then.time = abstime->tv_sec;
860 t_milli = abstime->tv_nsec/1000000;
862 if((then.time > now.time ||
863 (then.time == now.time && t_milli > n_milli))) {
864 if((t_milli -= n_milli) < 0) {
868 then.time -= now.time;
870 if ((then.time + (clock() / CLOCKS_PER_SEC)) <= 50000000) {
872 * Under NT, we can only wait for milliseconds, so we
873 * round up the wait time here.
875 rc = cond_wait_internal(cond, mutex,
876 ((then.time * 1000) + (t_milli)));
890 int pthread_cond_signal(pthread_cond_t *cond) {
892 cond_waiters_t *release_thread;
895 EnterCriticalSection(&cond->cs);
898 * remove the first waiting thread from the queue
899 * and resume his execution
901 if (queue_IsNotEmpty(&cond->waiting_threads)) {
902 release_thread = queue_First(&cond->waiting_threads,
904 queue_Remove(release_thread);
905 if (!SetEvent(release_thread->event)) {
910 LeaveCriticalSection(&cond->cs);
918 int pthread_cond_broadcast(pthread_cond_t *cond) {
920 cond_waiters_t *release_thread, *next_thread;
923 EnterCriticalSection(&cond->cs);
926 * Empty the waiting_threads queue.
928 if (queue_IsNotEmpty(&cond->waiting_threads)) {
929 for(queue_Scan(&cond->waiting_threads, release_thread,
930 next_thread, cond_waiter)) {
931 queue_Remove(release_thread);
932 if (!SetEvent(release_thread->event)) {
938 LeaveCriticalSection(&cond->cs);
946 int pthread_cond_destroy(pthread_cond_t *cond) {
950 DeleteCriticalSection(&cond->cs);
956 * A previous version of this file had code to check the waiter
957 * queue and empty it here. This has been removed in the hopes
958 * that it will aid in debugging.
964 int pthread_join(pthread_t target_thread, void **status) {
969 target = (thread_p) target_thread;
970 me = (thread_p) pthread_self();
974 * Check to see that the target thread is joinable and hasn't
975 * already been joined.
978 pthread_mutex_lock(&active_Q_mutex);
980 for(queue_Scan(&active_Q, cur, next, thread)) {
981 if (target == cur) break;
985 if ((!target->is_joinable) || (target->has_been_joined)) {
993 pthread_mutex_unlock(&active_Q_mutex);
997 target->waiter_count++;
998 while(target->running) {
999 pthread_cond_wait(&target->wait_terminate, &active_Q_mutex);
1003 * Only one waiter gets the status and is allowed to join, all the
1004 * others get an error.
1007 if (target->has_been_joined) {
1010 target->has_been_joined = 1;
1012 *status = target->rc;
1017 * If we're the last waiter it is our responsibility to remove
1018 * this entry from the terminated list and put it back in the
1022 target->waiter_count--;
1023 if (target->waiter_count == 0) {
1024 queue_Remove(target);
1025 pthread_mutex_unlock(&active_Q_mutex);
1028 pthread_mutex_unlock(&active_Q_mutex);
1038 * Note that we can't return an error from pthread_getspecific so
1039 * we return a NULL pointer instead.
1042 void *pthread_getspecific(pthread_key_t key) {
1044 char **tsd = TlsGetValue(tsd_index);
1046 if ((key > -1) && (key < PTHREAD_KEYS_MAX )) {
1047 rc = (void *) *(tsd + key);
1053 static int p_tsd_done;
1055 static void pthread_tsd_init(void) {
1056 pthread_mutex_init(&pthread_tsd_mutex, (const pthread_mutexattr_t*)0);
1060 int pthread_key_create(pthread_key_t *keyp, void (*destructor)(void *value)) {
1064 if (p_tsd_done || (!pthread_once(&pthread_tsd_once, pthread_tsd_init))) {
1065 if (!pthread_mutex_lock(&pthread_tsd_mutex)) {
1066 for(i=0;i<PTHREAD_KEYS_MAX;i++) {
1067 if (!keys[i].inuse) break;
1070 if (!keys[i].inuse) {
1072 keys[i].destructor = destructor;
1077 pthread_mutex_unlock(&pthread_tsd_mutex);
1088 int pthread_key_delete(pthread_key_t key) {
1091 if (p_tsd_done || (!pthread_once(&pthread_tsd_once, pthread_tsd_init))) {
1092 if ((key > -1) && (key < PTHREAD_KEYS_MAX )) {
1093 if (!pthread_mutex_lock(&pthread_tsd_mutex)) {
1094 keys[key].inuse = 0;
1095 keys[key].destructor = NULL;
1096 pthread_mutex_unlock(&pthread_tsd_mutex);
1110 int pthread_setspecific(pthread_key_t key, const void *value) {
1114 if (p_tsd_done || (!pthread_once(&pthread_tsd_once, pthread_tsd_init))) {
1115 if ((key > -1) && (key < PTHREAD_KEYS_MAX )) {
1116 if (!pthread_mutex_lock(&pthread_tsd_mutex)) {
1117 if (keys[key].inuse) {
1118 tsd = TlsGetValue(tsd_index);
1119 *(tsd + key) = (char *) value;
1123 pthread_mutex_unlock(&pthread_tsd_mutex);
1137 pthread_t pthread_self(void) {
1139 DWORD my_id = GetCurrentThreadId();
1141 (pthread_cache_done || pthread_once(&pthread_cache_once, create_once));
1142 (tsd_done || pthread_once(&global_tsd_once, tsd_once));
1144 pthread_mutex_lock(&active_Q_mutex);
1146 cur = TlsGetValue (tsd_pthread_index);
1150 * This thread's ID was not found in our list of pthread-API client
1151 * threads (e.g., those threads created via pthread_create). Create
1154 if ((cur = get_thread()) != NULL) {
1155 cur->is_joinable = 0;
1157 cur->native_thread = 1;
1158 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
1159 GetCurrentProcess(), &cur->t_handle, 0,
1160 TRUE, DUPLICATE_SAME_ACCESS);
1163 * We'll also need a place to store key data for this thread
1165 if ((cur->tsd = malloc(sizeof(char*) * PTHREAD_KEYS_MAX)) != NULL) {
1166 memset(cur->tsd, 0, (sizeof(char*) * PTHREAD_KEYS_MAX));
1168 TlsSetValue(tsd_index, (LPVOID)cur->tsd);
1169 TlsSetValue(tsd_pthread_index, (LPVOID)cur);
1172 * The thread_t structure is complete; add it to the active_Q
1174 queue_Prepend(&active_Q, cur);
1177 * We were able to successfully insert a new entry into the
1178 * active_Q; however, when this thread terminates, we will need
1179 * to know about it. The pthread_sync_terminate_thread() routine
1180 * will make sure there is a dedicated thread waiting for any
1181 * native-thread entries in the active_Q to terminate.
1183 pthread_sync_terminate_thread();
1187 pthread_mutex_unlock(&active_Q_mutex);
1189 return (void *) cur;
1192 int pthread_equal(pthread_t t1, pthread_t t2) {
1196 int pthread_attr_destroy(pthread_attr_t *attr) {
1202 int pthread_attr_init(pthread_attr_t *attr) {
1206 attr->is_joinable = PTHREAD_CREATE_JOINABLE;
1214 int pthread_attr_getdetachstate(pthread_attr_t *attr, int *detachstate) {
1217 if ((attr != NULL) && (detachstate != NULL)) {
1218 *detachstate = attr->is_joinable;
1225 int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate) {
1228 if ((attr != NULL) && ((detachstate == PTHREAD_CREATE_JOINABLE) ||
1229 (detachstate == PTHREAD_CREATE_DETACHED))) {
1230 attr->is_joinable = detachstate;
1237 void pthread_exit(void *status) {
1238 thread_p me = (thread_p) pthread_self();
1241 * Support pthread_exit for thread's created by calling pthread_create
1242 * only. Do this by using an exception that will transfer control
1243 * back to afs_pthread_create_stub. Store away our status before
1246 * If this turns out to be a native thread, the exception will be
1247 * unhandled and the process will terminate.
1251 RaiseException(PTHREAD_EXIT_EXCEPTION, 0, 0, NULL);