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++
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++
Just use static and __thread in your function.
Example:
You can also use the C++11 thread local storage additions if you have access to C++11.
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
The current C standard has no model for threads or alike, so you can't get an answer, there.
The utility foreseen by POSIX for that is
pthread_[gs]etspecific
.The next version of the C standard adds threads and has a concept of thread local storage.
You can make your own thread specific local storage as singleton per thread ID. Something like this:
GetThreadId(); is a platform specific function for determining caller's thread id. Something like this:
Now, within a thread function you can use it's local storage: