C语言pthread_cond_wait与pthread_cond_signal的使用

来源:互联网 发布:ios更新系统 数据丢失 编辑:程序博客网 时间:2024/03/28 21:49

原文:http://pages.cs.wisc.edu/~remzi/OSTEP/threads-cv.pdf

举例:

#include <stdio.h>#include <stdlib.h>#include <pthread.h>int done = 0;pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;pthread_cond_t cond = PTHREAD_COND_INITIALIZER;void thread_exit(){    pthread_mutex_lock(&mutex);    done = 1;    pthread_cond_signal(&cond);    pthread_mutex_unlock(&mutex);}void *child(void *args){    printf("child\n");    thread_exit();    return NULL;}void thread_join(){    pthread_mutex_lock(&mutex);    while(done == 0)        pthread_cond_wait(&cond, &mutex);    pthread_mutex_unlock(&mutex);}int main(){    pthread_t p;    printf("parent begin\n");    pthread_create(&p, NULL, child, NULL);    thread_join();    printf("parend end\n");    pthread_join(p, NULL);    return 0;}

运行状态存在两种情况。


第一,父线程创建了子线程后,继续运行本身后续代码,于是立即调用thread_join函数。在这个函数中,会对mutex加锁,并判断子线程是否结束。如果没结束,则自己睡眠;如果结束,则解锁mutex。最终,子线程运行,调用thread_exit函数来唤醒父线程。


第二,父线程创建了子线程后,子线程立即运行,将变量done设置为1,并调用thread_exit函数唤醒一个线程(但由于没有线程睡眠,于是没有任何影响)。父线程调用thread_join函数,发现变量done为1,于是不再等待,立即结束。

0 0
原创粉丝点击