关于条件变量(C语言)
由于条件变量必须和互斥锁协同使用,所以在介绍条件前会先介绍一下互斥锁(本文目前只介绍C语言,C++的条件变量可能后期会介绍)
1、互斥锁
从本质上来说,互斥锁是一把锁,保护共享资源免受并发影响的问题,同一时间只能有一个线程可以访问被保护的资源,从而防止竞态而产生不好的结果
1、C语言互斥锁的基本使用
pthread_mutex_init:初始化
pthread_mutex_lock:上锁
pthread_mutex_trylock:如果mutex已经被其他线程上锁,该操作会一直阻塞在这个地方,如果不想一直阻塞在这个地方,trylock若此时互斥量没有被上锁,函数会返回0,并对该互斥量进行上锁,如果被上锁了,就立刻返回ebusy
pthread_mutex_unlock:解锁
2、条件变量
1、引入的原因
互斥锁存在的问题:明显的缺点就是它只有锁定和非锁定两种状态,多个线程同时访问一个共享资源,并不知道合适应该使用共享资源,在临界区增加判断语句,效率不高且难实现,而条件变量能在条件成立时触发相应的线程,进行变量的修改和访问
条件变量通过允许线程阻塞和等待另一个线程发送信号的方法弥补了互斥锁的不足,常和互斥锁一起使用
2、基本函数
pthread_cond_init:创建
pthread_cond_singal:激活一个等待等待该条件的线程
pthread_cond_broadcast:激活所有等待的线程
pthread_cond_wait:等待
pthread_cond_timewait:在限定的时间内等待
pthread_cond_destory:销毁
相关示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | #include<stdio.h> #include<unistd.h> #include<pthread.h> pthread_mutex_t mutex; pthread_cond_t isthree; int i = 1; void * thread1( void * arg) { for (i = 1; i <= 9; i++) { pthread_mutex_lock(&mutex); if (i % 3 == 0) { pthread_cond_signal(&isthree); } else { printf( "this is thread1 i is: %d\n" , i); } pthread_mutex_unlock(&mutex); sleep(1); } } void * thread2( void * arg) { printf( "aaaa\n" ); while (i <= 9) { pthread_mutex_lock(&mutex); if (i % 3 != 0) { pthread_cond_wait(&isthree, &mutex); printf( "this is thread2 i is: %d\n" , i); } pthread_mutex_unlock(&mutex); sleep(1); } } int main() { pthread_mutex_init(&mutex, NULL); pthread_cond_init(&isthree, NULL); pthread_t t1; pthread_t t2; pthread_create(&t1, NULL, thread1, NULL); pthread_create(&t2, NULL, thread2, NULL); pthread_join(t2, NULL); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&isthree); return 0; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)