user7673022
user7673022

Reputation:

How to make multiple POSIX threads wait for another to begin

I am working on a program that uses multithreading to simulate people and an elevator. There is one elevator and multiple people that ride the elevator.

Thus far, I am attempting to create one thread per person, and one thread for the elevator. However, the people need to wait for the elevator to get created before they can start performing their actions, and the elevator needs to wait for all of the people to get created before it starts moving.

I looked into pthread_join(), but it looks like that waits for a thread to FINISH, which is not what I want.

Upvotes: 2

Views: 1211

Answers (1)

user9614249
user9614249

Reputation:

You can use barriers.

From the pthread Barriers section of randu.org's pthread tutorial:

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.

In other words, you can create a barrier with n and any threads that calls pthread_barrier_wait will wait until n calls to pthread_barrier_wait have been made.

Below is a simple example where all three threads will print "Before" prior to any thread printing "After".

#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");
}

Run the code here

Upvotes: 3

Related Questions