关于pthread_cond_wait

newarr newarr 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
在看Unix编程关于多线程的内容,看到pthread_cond_wait觉得很费解,为何在锁定数据队列的时候等待?那写进程不是完全没机会解锁来往队列里写东西释放该等待队列?还有个问题就是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的用法进行了详细的分析介绍,需要的朋友可以过来参考下

weixin_38647517

pthread_cond_wait详解

一篇博客内容 pthread_cond_wait详解

记得最初的梦想

信号pthread_cond_wait

信号pthread_cond_wait信号pthread_cond_wait信号pthread_cond_wait信号pthread_cond_wait信号pthread_cond_wait

nuoshueihe

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来实现线程间的同步与通信。

w1x2y3
评论 3
收藏 已收藏
分享
返回顶部
newarr
其它技术问题 3,880 成员 9,044 内容