pthread_cond_wait

前要先加锁
pthread_cond_wait内部会解锁,然后等待条件变量被其它线程激活
pthread_cond_wait被激活后会再自动加锁
激活线程:
加锁(和等待线程用同一个锁)
pthread_cond_signal发送信号
解锁

线程便会调用pthread_cond_wait阻塞自己,但是它持有的锁怎么办呢,如果他不归还操作系统,那么其他线程将会无法访问公有资源。这就要追究一下pthread_cond_wait的内部实现机制,当pthread_cond_wait被调用线程阻塞的时候,pthread_cond_wait会自动释放互斥锁。释放互斥锁的时机是什么呢:是线程从调用pthread_cond_wait到操作系统把他放在线程等待队列之后

#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int count = 0;

void* decrement(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
if (count == 0)
pthread_cond_wait(&cond, &mutex);
count--;
printf("消费一%d\n", count);
pthread_mutex_unlock(&mutex);
sleep(7);
}

return NULL;
}

void* decrement1(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
if (count == 0)
pthread_cond_wait(&cond, &mutex);
count--;
printf("消费二%d\n", count);
pthread_mutex_unlock(&mutex);
sleep(5);
}
return NULL;
}
void* increment(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
count++;
printf("生产%d\n", count);
if (count != 0)
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(2);
}
return NULL;
}

int main(int argc, char* argv[]) {
pthread_t tid_in, tid_de, tid_de1;
pthread_create(&tid_de, NULL, (void*)decrement, NULL);
pthread_create(&tid_in, NULL, (void*)increment, NULL);
pthread_create(&tid_de1, NULL, (void*)decrement1, NULL);
while (1);
pthread_join(tid_de, NULL);
pthread_join(tid_in, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}

posted @   MoonXu  阅读(322)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
历史上的今天:
2020-07-22 腾讯云获取公网ip
2020-07-22 ifconfig添加或删除ip
2020-07-22 程序中tar压缩文件
2020-07-22 sprintf出错
2020-07-22 在程序中执行改变目录操作
2019-07-22 linux发行版安装vmci.sys版本错误
2019-07-22 linux命令
点击右上角即可分享
微信分享提示