Jack
Jack

Reputation: 996

Mutex lock either hangs or doesn't work

I'm using pthreads to create a child process alongside the parent process. I'm trying to use mutex to stop after the first print statement in the child process and resume after the second print statement in the parent process:

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

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *print(void *attr)
{
printf("I am the child process\n");
pthread_mutex_lock(&lock);
pthread_cond_wait(&cond, &lock);
printf("The child process is done\n");
pthread_mutex_unlock(&lock);
return 0;
}

int main()
{

pthread_t child;
pthread_mutex_lock(&lock);
printf("I am the parent process\n");
pthread_create(&child, NULL, print, NULL);
pthread_join(child, NULL);
printf("The parent process is done\n");
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
return 0;
}

The original output is as follows:

I am the parent process
I am the child process
The child process is done
The parent process is done

The output I'm looking for is as follows:

I am the parent process
I am the child process
The parent process is done
The child process is done

I can't for the life of me figure out how to achieve this with mutex, the closest I've come is for it to reach the first two statements before hanging indefinitely. I've also had the original output, as if the mutex statements are doing nothing.

Could anyone help me figure this out? Thanks in advance.

Upvotes: 1

Views: 1820

Answers (1)

Steve Emmerson
Steve Emmerson

Reputation: 7832

You just need better signaling between the parent and child threads. This should do it:

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

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  cond = PTHREAD_COND_INITIALIZER;
int             child_done = 0;
int             parent_done = 0;

void *print(void *attr)
{
    printf("I am the child process\n");
    pthread_mutex_lock(&lock);
    child_done = 1;
    pthread_cond_broadcast(&cond); // Because this thread also waits
    while (!parent_done)
        pthread_cond_wait(&cond, &lock);
    printf("The child process is done\n");
    pthread_mutex_unlock(&lock);
    return 0;
}

int main()
{
    pthread_t child;
    pthread_mutex_lock(&lock);
    printf("I am the parent process\n");
    pthread_create(&child, NULL, print, NULL);
    while (!child_done)
        pthread_cond_wait(&cond, &lock);
    printf("The parent process is done\n");
    parent_done = 1;
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&lock);
    pthread_join(child, NULL);
    return 0;
}

Upvotes: 2

Related Questions