Home > Back-end >  Stack Memory and Multithreading in C
Stack Memory and Multithreading in C

Time:09-18

Usually, when I have two concurrent running threads, and each thread calls the same function, there are two instances of the function running in parallel, one in each thread's stack memory. No race condition.

My question is what if I have a global struct with a function pointer.

If I run that function in each thread, from the global struct, is that a race condition? Is there only one copy of the function's variables in the application stack?

Do I need a mutex/semaphore?

CodePudding user response:

I suspect it is not a race condition because the act of calling a function from a function pointer, should be effectively the same as calling a function

Your suspicion is correct. If thread A calls some function, then the activation record for that call (i.e., where the local variables for the call reside) will be on thread A's stack. If thread B simultaneously calls the same function, then that activation record will be on thread B's stack.

It does not matter how either of the two threads knew which function to call. It's the same regardless of whether the address of the function was hard-wired into the code, or whether they got the function address from a "function pointer" variable in a struct.

CodePudding user response:

If I run that function simultaneously in each thread, from the global struct, is that a race condition?

The rule is: if two (or more) threads can both access the same data, and at least one of the threads might modify the data, then there is a race condition. In that situation, you can avoid the race condition by having each thread lock a mutex before accessing the data, and unlock the mutex afterwards, so that it is guaranteed that no other thread will modify the data while that thread is reading and/or modifying it.

If both threads are only reading the data and will never modify it, then no mutex is necessary.

Is there only one copy of the function's variables in the application stack?

I don't know what "the application stack" is, but if you are asking if there is only one copy of the global struct, the answer is yes.

If by "the function's variables" you mean local variables that are declared inside the function body -- those are located separately in each thread's stack and not shared across threads (although if the local variable is a pointer, the object it points to might be shared).

  • Related