Skip to content

Commit 7c11a7a

Browse files
committed
[mypyc] Foundations for supporting thread-local C variables
Use e.g. `CPyThreadLocal int x;` to define a thread-local variable that should work across most compilers we might want to support.
1 parent fb5520a commit 7c11a7a

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

mypyc/lib-rt/mypyc_util.h

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,31 @@
2323
#define CPy_NOINLINE
2424
#endif
2525

26+
#ifndef Py_GIL_DISABLED
27+
28+
// Everything is running in the same thread, so no need for thread locals
29+
#define CPyThreadLocal
30+
31+
#else
32+
33+
// 1. Use C11 standard thread_local storage, if available
34+
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)
35+
#define CPyThreadLocal _Thread_local
36+
37+
// 2. Microsoft Visual Studio fallback
38+
#elif defined(_MSC_VER)
39+
#define CPyThreadLocal __declspec(thread)
40+
41+
// 3. GNU thread local storage for GCC/Clang targets that still need it
42+
#elif defined(__GNUC__) || defined(__clang__)
43+
#define CPyThreadLocal __thread
44+
45+
#else
46+
#error "Cannot define CPyThreadLocal for this compiler/target"
47+
#endif
48+
49+
#endif // Py_GIL_DISABLED
50+
2651
// INCREF and DECREF that assert the pointer is not NULL.
2752
// asserts are disabled in release builds so there shouldn't be a perf hit.
2853
// I'm honestly kind of surprised that this isn't done by default.

0 commit comments

Comments
 (0)