MultiThread Question
-
Hi It is my understanding that local variables of a Multithread application i.e those declared on the stack for each function are thread safe. Each thread BP,SP registers have a unique address so variables declared on the stack are all unique to each thread. Am I correct in understanding this ? Thanks
-
Hi It is my understanding that local variables of a Multithread application i.e those declared on the stack for each function are thread safe. Each thread BP,SP registers have a unique address so variables declared on the stack are all unique to each thread. Am I correct in understanding this ? Thanks
Each thread has its own stack. When calling a function from different threads, the local function variables reside on the stack of the thread from where the function has been called. So it is thread safe. But note that this does not apply to local
static
variables. While also local variables (can't be accessed from outside of the function), there is only one instance of such variables. Accessing them must be guarded (locks, atomic operations) and the function must not return a pointer to them to make the function thread safe. -
Each thread has its own stack. When calling a function from different threads, the local function variables reside on the stack of the thread from where the function has been called. So it is thread safe. But note that this does not apply to local
static
variables. While also local variables (can't be accessed from outside of the function), there is only one instance of such variables. Accessing them must be guarded (locks, atomic operations) and the function must not return a pointer to them to make the function thread safe.Thanks I think of static local variables as global. I am using a local variable as a switch if local variable BOOL foo = TRUE for thread A, It (BOOL foo is not the same) for thread B is there any reason in a Multithread application I would have to guard them (local variables non static ) there are no references to them by pointers Thanks
-
Thanks I think of static local variables as global. I am using a local variable as a switch if local variable BOOL foo = TRUE for thread A, It (BOOL foo is not the same) for thread B is there any reason in a Multithread application I would have to guard them (local variables non static ) there are no references to them by pointers Thanks
You only have to guard shared variables (like static variables). Variables on the stack are safe.
-
You only have to guard shared variables (like static variables). Variables on the stack are safe.