关于pthread_cond_wait
#include <pthread.h>
#include <unistd.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct node {
int n_number;
struct node *n_next;
} *head = NULL;
/*[thread_func]*/
static void cleanup_handler(void *arg)
{
printf("Cleanup handler of second thread.\n");
free(arg);
(void)pthread_mutex_unlock(&mtx);
}
static void *thread_func(void *arg)
{
struct node *p = NULL;
pthread_cleanup_push(cleanup_handler, p);
while (1) {
pthread_mutex_lock(&mtx);
while (head == NULL)
pthread_cond_wait(&cond, &mtx);
p = head;
head = head->n_next;
printf("Got %d from front of queue\n", p->n_number);
free(p);
pthread_mutex_unlock(&mtx);
}
pthread_cleanup_pop(0);
return 0;
/*EC_CLEANUP_BGN
(void)pthread_mutex_unlock(&mtx);
EC_FLUSH("thread_func")
return 1;
EC_CLEANUP_END*/
}
/*[]*/
int main(void)
{
pthread_t tid;
int i;
struct node *p;
pthread_create(&tid, NULL, thread_func, NULL);
/*[tx6-main]*/
for (i = 0; i < 10; i++) {
p = malloc(sizeof(struct node));
p->n_number = i;
pthread_mutex_lock(&mtx);
p->n_next = head;
head = p;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
sleep(1);
}
printf("thread 1 wanna end the line.So cancel thread 2.\n");
pthread_cancel(tid);
pthread_join(tid, NULL);
printf("All done -- exiting\n");
return 0;
/*[]*/
/*EC_CLEANUP_BGN
return EXIT_FAILURE;
EC_CLEANUP_END*/
}
相关推荐
pthread_cond_wait() 用法深入分析
以下是对pthread_cond_wait的用法进行了详细的分析介绍,需要的朋友可以过来参考下
pthread_cond_wait详解
一篇博客内容 pthread_cond_wait详解
信号pthread_cond_wait
信号pthread_cond_wait信号pthread_cond_wait信号pthread_cond_wait信号pthread_cond_wait信号pthread_cond_wait
pthread_cond_wait详解[项目代码]
本文详细介绍了pthread_cond_wait函数的使用及其内部机制。pthread_cond_wait通常与pthread_cond_signal配对使用,用于线程间的条件变量同步。文章首先介绍了条件变量的初始化和销毁函数pthread_cond_init和pthread_cond_destroy,并解释了为什么在使用pthread_cond_wait时需要加锁。接着,文章深入分析了pthread_cond_wait的内部实现机制,包括其如何自动释放和重新获取互斥锁,以及为什么需要使用while循环而非if语句来检查条件。此外,文章还提供了两个示例代码,分别演示了pthread_cond_wait和pthread_cond_signal的基本用法以及生产者-消费者模型的应用。最后,文章提到了pthread_cleanup_push和pthread_cleanup_pop等函数,为后续内容做了铺垫。
pthread_cond_wait详解[源码]
本文详细介绍了C语言中pthread_cond_wait函数的原理及其使用方法。pthread_cond_wait用于阻塞当前线程,等待其他线程通过pthread_cond_signal或pthread_cond_broadcast唤醒它。该函数必须与pthread_mutex配套使用,进入wait状态时会自动释放mutex,唤醒时又自动获取mutex。文章还讨论了pthread_cond_signal的唤醒机制,指出其最多只唤醒一个线程,但在多处理器上可能同时唤醒多个线程。为避免惊群现象,推荐使用while循环进行条件判断。此外,文中提供了一个生产者-消费者模型的代码示例,展示了如何在实际应用中使用pthread_cond_wait和pthread_cond_signal来实现线程间的同步与通信。


其它技术问题
