summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJakob Kaivo <jkk@ung.org>2019-01-29 17:16:47 -0500
committerJakob Kaivo <jkk@ung.org>2019-01-29 17:16:47 -0500
commit84e864c530a3a24348bfb453a23a2ce0abcf1ec0 (patch)
tree89f72a5b14394c4b7ba47cf61ed003844a0d6c03
parentddd89da154b3f18d71e1284abeea636c87bbd6bf (diff)
draft thread-local state based on C11 TLS or pthreads
-rw-r--r--nonstd/static/thread.h34
1 files changed, 34 insertions, 0 deletions
diff --git a/nonstd/static/thread.h b/nonstd/static/thread.h
index 00b40861..db66c0b7 100644
--- a/nonstd/static/thread.h
+++ b/nonstd/static/thread.h
@@ -1,5 +1,39 @@
+#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 201101L
+
+static struct per_thread *per_thread(void)
+{
+ _Thread_local static struct per_thread pt = {0};
+ return &pt;
+}
+
+#elif defined _POSIX_C_SOURCE && _POSIX_C_SOURCE >= 199506L
+#include <pthread.h>
+
+static pthread_key_t __per_thread_key;
+
+static void _make_key(void)
+{
+ pthread_key_create(&key, NULL);
+}
+
+static struct per_thread *per_thread(void)
+{
+ static pthread_once_t key_once = PTHREAD_ONCE_INIT;
+ struct per_thread *pt;
+ pthread_once(&key_once, make_key);
+ if ((pt = pthread_getspecific(key)) == NULL) {
+ pt = calloc(1, sizeof (*pt));
+ pthread_setspecific(key, pt);
+ }
+ return pt;
+}
+
+#else
+
static struct per_thread *per_thread(void)
{
static struct per_thread pt = {0};
return &pt;
}
+
+#endif