Skip to content

Instantly share code, notes, and snippets.

@kddnewton
Last active January 6, 2025 13:49
Show Gist options
  • Save kddnewton/080aa4a4d2a3acd3e052948122631e34 to your computer and use it in GitHub Desktop.
Save kddnewton/080aa4a4d2a3acd3e052948122631e34 to your computer and use it in GitHub Desktop.
TLS macOS weirdness
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
static int value = 0xDEADBEEF;
static _Thread_local void *tls = &value;
static pthread_key_t key;
void *worker(void *arg) {
tls = (void*)0xCAFEBABE;
pthread_setspecific(key, tls);
fprintf(
stderr,
"[worker]\n"
" automatic=%p\n"
" &automatic=%p\n"
" dynamic=%p\n",
tls,
&tls,
pthread_getspecific(key)
);
return NULL;
}
void destructor(void *arg) {
fprintf(
stderr,
"[destructor]\n"
" automatic=%p\n"
" &automatic=%p\n"
" dynamic=%p\n",
tls,
&tls,
arg
);
}
int main(void) {
fprintf(stderr, "automatic default = %p\n", tls);
pthread_key_create(&key, destructor);
pthread_t thread;
pthread_create(&thread, NULL, worker, NULL);
pthread_join(thread, NULL);
pthread_key_delete(key);
return EXIT_SUCCESS;
}
automatic default = 0x1008b8000
[worker]
automatic=0xcafebabe
&automatic=0x600001b18030
dynamic=0xcafebabe
[destructor]
automatic=0x1008b8000
&automatic=0x600001b18030
dynamic=0xcafebabe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment