1 #include "threads_impl.h"
2 
3 // C11 does not define any way for applications to know the maximum
4 // number of tss_t slots. pthreads, however, does, via the
5 // PTHREAD_KEYS_MAX constant. So we allow that bit of pthreads to
6 // bleed over here (and into sysconf, which also reports the value)
7 // rather than go through some circuituous pattern to define an
8 // internal constant that's just the same as the pthread one.
9 
10 typedef void (*key_t)(void*);
_Atomic(key_t)11 static _Atomic(key_t) keys[PTHREAD_KEYS_MAX];
12 
13 static void nodtor(void* dummy) {}
14 
tss_create(tss_t * k,void (* dtor)(void *))15 int tss_create(tss_t* k, void (*dtor)(void*)) {
16     unsigned i = (uintptr_t)&k / 16 % PTHREAD_KEYS_MAX;
17     unsigned j = i;
18 
19     if (!dtor)
20         dtor = nodtor;
21     do {
22         key_t expected = NULL;
23         if (atomic_compare_exchange_strong(&keys[j], &expected, dtor)) {
24             *k = j;
25             return 0;
26         }
27     } while ((j = (j + 1) % PTHREAD_KEYS_MAX) != i);
28     return EAGAIN;
29 }
30 
tss_delete(tss_t k)31 void tss_delete(tss_t k) {
32     atomic_store(&keys[k], NULL);
33 }
34 
__thread_tsd_run_dtors(void)35 void __thread_tsd_run_dtors(void) {
36     thrd_t self = __thrd_current();
37     int i, j, not_finished = self->tsd_used;
38     for (j = 0; not_finished && j < TSS_DTOR_ITERATIONS; j++) {
39         not_finished = 0;
40         for (i = 0; i < PTHREAD_KEYS_MAX; i++) {
41             if (self->tsd[i] && atomic_load(&keys[i])) {
42                 void* tmp = self->tsd[i];
43                 self->tsd[i] = 0;
44                 atomic_load(&keys[i])(tmp);
45                 not_finished = 1;
46             }
47         }
48     }
49 }
50