Search code examples
cmultithreadingstack-memory

Stack Memory and Multithreading in C


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?


Solution

  • 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.