Johnathan Johnathan - 2 months ago 12
C++ Question

Will my pthread wait or will the main thread wait?

So i'm getting the hang of using c/c++ but i'm still a bit misguided. I'm also trying to learn synchronization at the same time so things aren't going perfect.

So my potential problem here is,


  • I have a Node object, Node has a method called run. Run creates a pthread and passes a function pointer of a function called compute() as a parameter.

  • The Compute function has one parameter which is the Node that called Run()

  • The Compute function will then access a Semaphore (sem_t) that is a field of the Node object passed as a parameter and will call sem_wait(Node.sem) on that semaphore.



If I do this, will the newly created thread that is running the compute function actually call the sem_wait and do the defined behavior. Or will the the process that originally created the Node call sem_wait?

Answer

The sem_wait call will execute in the thread in which it was called (as @Jason C points out in his comment). From what you've described that happens in run after the thread has been started, hence sem_wait will be executed in the first thread.

You seem to be thinking that because the Node object is used in both threads that somehow has an effect on which thread will execute a call. It doesn't. Threads share memory space so your Node object can be used in any thread within a process. That's when you start getting into thread safety issues.