Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define thread-local local static variables?

Tags:

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++

like image 731
Hayri Uğur Koltuk Avatar asked Sep 30 '11 06:09

Hayri Uğur Koltuk


People also ask

Are static variables ThreadLocal?

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.

What is ThreadLocal variable in C?

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.

What is __ thread in C?

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.

Is static local variable thread safe?

So yes, you're safe.


1 Answers

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

like image 97
Rom Avatar answered Nov 12 '22 21:11

Rom