1 #include "pthread_impl.h"
3 volatile size_t __pthread_tsd_size = sizeof(void *) * PTHREAD_KEYS_MAX;
4 void *__pthread_tsd_main[PTHREAD_KEYS_MAX] = { 0 };
6 static void (*keys[PTHREAD_KEYS_MAX])(void *);
8 static pthread_rwlock_t key_lock = PTHREAD_RWLOCK_INITIALIZER;
10 static pthread_key_t next_key;
12 static void nodtor(void *dummy)
16 static void dirty(void *dummy)
25 static void clean_dirty_tsd_callback(void *p)
27 struct cleanup_args *args = p;
28 pthread_t self = __pthread_self();
30 for (i=0; i<PTHREAD_KEYS_MAX; i++) {
31 if (keys[i] == dirty && self->tsd[i])
34 /* Arbitrary choice to avoid data race. */
35 if (args->caller == self) args->ret = 0;
38 static int clean_dirty_tsd(void)
40 struct cleanup_args args = {
41 .caller = __pthread_self(),
44 __pthread_key_delete_synccall(clean_dirty_tsd_callback, &args);
48 int __pthread_key_create(pthread_key_t *k, void (*dtor)(void *))
50 pthread_key_t j = next_key;
51 pthread_t self = __pthread_self();
54 /* This can only happen in the main thread before
55 * pthread_create has been called. */
56 if (!self->tsd) self->tsd = __pthread_tsd_main;
58 /* Purely a sentinel value since null means slot is free. */
59 if (!dtor) dtor = nodtor;
61 pthread_rwlock_wrlock(&key_lock);
64 keys[next_key = *k = j] = dtor;
65 pthread_rwlock_unlock(&key_lock);
67 } else if (keys[j] == dirty) {
70 } while ((j=(j+1)%PTHREAD_KEYS_MAX) != next_key);
72 /* It's possible that all slots are in use or __synccall fails. */
73 if (!found_dirty || clean_dirty_tsd()) {
74 pthread_rwlock_unlock(&key_lock);
78 /* If this point is reached there is necessarily a newly-cleaned
79 * slot to allocate to satisfy the caller's request. Find it and
80 * mark any additional previously-dirty slots clean. */
81 for (j=0; j<PTHREAD_KEYS_MAX; j++) {
82 if (keys[j] == dirty) {
84 keys[next_key = *k = j] = dtor;
92 pthread_rwlock_unlock(&key_lock);
96 int __pthread_key_delete_impl(pthread_key_t k)
98 pthread_rwlock_wrlock(&key_lock);
100 pthread_rwlock_unlock(&key_lock);
104 void __pthread_tsd_run_dtors()
106 pthread_t self = __pthread_self();
108 for (j=0; self->tsd_used && j<PTHREAD_DESTRUCTOR_ITERATIONS; j++) {
109 pthread_rwlock_rdlock(&key_lock);
111 for (i=0; i<PTHREAD_KEYS_MAX; i++) {
112 void *val = self->tsd[i];
113 void (*dtor)(void *) = keys[i];
115 if (val && dtor && dtor != nodtor && dtor != dirty) {
116 pthread_rwlock_unlock(&key_lock);
118 pthread_rwlock_rdlock(&key_lock);
121 pthread_rwlock_unlock(&key_lock);
125 weak_alias(__pthread_key_create, pthread_key_create);