c - 如何让多个 POSIX 线程等待另一个线程开始

标签 c multithreading pthreads posix

我正在开发一个使用多线程来模拟人和电梯的程序。有一部电梯,多人乘坐电梯。

到目前为止,我正在尝试为每个人创建一个线程,并为电梯创建一个线程。然而,人们需要等待电梯被创建才能开始执行他们的操作,而电梯需要等待所有的人被创建才能开始移动。

我研究了 pthread_join(),但看起来它等待线程完成,这不是我想要的。

最佳答案

您可以使用障碍。

来自 randu.org's pthread tutorial 的 pthread Barriers 部分:

pthreads can participate in a barrier to synchronize to some point in time. Barrier objects are initialized like mutexes or condition variables, except there is one additional parameter, count. The count variable defines the number threads that must join the barrier for the barrier to reach completion and unblock all threads waiting at the barrier.

换句话说,您可以使用 n 创建屏障,并且任何调用 pthread_barrier_wait 的线程都将等待,直到 n 次调用 pthread_barrier_wait 已完成。

下面是一个简单的示例,其中所有三个线程都将在任何线程打印“After”之前打印“Before”。

#include <pthread.h>
#include <stdio.h>

pthread_barrier_t barrier; 

void* foo(void* msg) {
    printf("%s: before\n", (char*)msg);

    // No thread will move on until all three threads have reached this point
    pthread_barrier_wait(&barrier);

    printf("%s: after\n", (char*)msg);
}

int main() {

    // Declare three threads
    int count = 3;
    pthread_t person_A, person_B, elevator;

    // Create a barrier that waits for three threads
    pthread_barrier_init(&barrier, NULL, count); 

    // Create three threads
    pthread_create(&person_A, NULL, foo, "personA");
    pthread_create(&person_B, NULL, foo, "personB");
    pthread_create(&elevator, NULL, foo, "elevator");

    pthread_join(person_A, NULL);
    pthread_join(person_B, NULL);
    pthread_join(elevator, NULL);
    printf("end\n");
}

运行代码here

关于c - 如何让多个 POSIX 线程等待另一个线程开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53125648/

相关文章:

c# - 为单独的线程使用不同的 .config 文件 (.NET/C#)

android - java.lang.RuntimeException : Can't create handler inside thread that has not called Looper. 准备();

c - 创建多个具有互斥锁和不同生命周期的线程

c++ - usleep 是否创建线程取消点?

c - 如何使用自己的自定义函数(不是 vprintf 等)处理可变参数(通过省略号传递)?

检查值是否已存在于数组中

c - 使用 C 中的 fork 扫描目录并同时处理特定文件

计算 Pi 多线程 pthread

c++ - 在 For 循环中创建多个线程来处理二维数组

c - 循环遍历函数指针数组