How to define local static variables (that keeps its value between function calls) that are not shared among different threads?
I am looking for an answer both in C and C++
static final ThreadLocal variables are thread safe. static makes the ThreadLocal variable available across multiple classes for the respective thread only. it's a kind of Global variable decaration of the respective thread local variables across multiple classes.
Thread-local storage (TLS) is a mechanism by which variables are allocated such that there is one instance of the variable per extant thread. The run-time model GCC uses to implement this originates in the IA-64 processor-specific ABI, but has since been migrated to other processors as well.
The __thread storage class marks a static variable as having thread-local storage duration. This means that, in a multi-threaded application, a unique instance of the variable is created for each thread that uses it, and destroyed when the thread terminates.
So yes, you're safe.
on Windows using Windows API: TlsAlloc()/TlsSetValue()/TlsGetValue()
on Windows using compiler intrinsic: use _declspec(thread)
on Linux (other POSIX???) : get_thread_area() and related
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With