简体   繁体   English

我的 pthread 会等待还是主线程会等待?

[英]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.所以我已经掌握了使用 c/c++ 的窍门,但我仍然有点被误导了。 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.我有一个 Node 对象,Node 有一个名为 run 的方法。 Run creates a pthread and passes a function pointer of a function called compute() as a parameter. Run 创建一个 pthread 并传递一个名为 compute() 的函数的函数指针作为参数。

  • The Compute function has one parameter which is the Node that called Run() Compute 函数有一个参数,它是调用 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.然后,Compute 函数将访问作为参数传递的 Node 对象字段的信号量 (sem_t),并将对该信号量调用 sem_wait(Node.sem)。

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.如果我这样做,运行计算函数的新创建的线程是否会实际调用 sem_wait 并执行定义的行为。 Or will the the process that originally created the Node call sem_wait?还是最初创建 Node 的进程会调用 sem_wait?

The sem_wait call will execute in the thread in which it was called (as @Jason C points out in his comment). sem_wait调用将在调用它的线程中执行(正如@Jason C 在他的评论中指出的那样)。 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.根据您所描述的在线程启动后run中发生的情况,因此sem_wait将在第一个线程中执行。

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.您似乎在想,因为Node对象在两个线程中都使用,这会以某种方式影响哪个线程将执行调用。 It doesn't.它没有。 Threads share memory space so your Node object can be used in any thread within a process.线程共享内存空间,因此您的Node对象可以在进程内的任何线程中使用。 That's when you start getting into thread safety issues.那是您开始进入线程安全问题的时候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM