繁体   English   中英

互斥锁已挂起或不起作用

[英]Mutex lock either hangs or doesn't work

我正在使用pthreads与父进程一起创建子进程。 我试图使用互斥锁在子进程中的第一个print语句之后停止并在父进程中的第二个print语句之后恢复:

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

原始输出如下:

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

我正在寻找的输出如下:

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

我无法为自己的一生弄清楚如何使用互斥锁来实现这一目标,我最接近的是它可以无限期地挂起前两个语句。 我也有原始输出,好像互斥体语句什么也不做。

谁能帮我解决这个问题? 提前致谢。

您只需要在父线程和子线程之间更好地发出信号即可。 应该这样做:

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

暂无
暂无

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

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