直接上代码,主要用到sem_trywait & sem_post

#include<stdio.h> #include<pthread.h> #include<stdlib.h> #include<string.h> #include<semaphore.h> #include<time.h> sem_t sem_cal; sem_t sem_times; typedef struct _cal_ { int sum; }CAL; CAL cal; void *calculate(void*arg) { int i; int sum; for(i = 0; i < 3; i++) { cal.sum = cal.sum + i; sleep(1); } sem_post(&sem_cal); } void *sum(void *arg) { sem_wait(&sem_cal); printf("the sum is %d\n",cal.sum); sem_post(&sem_times); } void do_other() { printf("do others\n"); } void *times(void *arg) { //do others while(1) { if(!sem_trywait(&sem_times)) { printf("the times is %d\n",cal.sum * cal.sum); break; } do_other(); sleep(1); } } int main(void) { int ret=-1; pthread_t th[3]; sem_init(&sem_cal,0,0); sem_init(&sem_times,0,0); ret = pthread_create(&th[0],NULL,calculate,NULL); if (ret != 0) { printf("Pthread_create failed\n"); return -1; } ret = pthread_create(&th[1],NULL,sum,NULL); if (ret != 0) { printf("Pthread_create failed\n"); return -1; } ret = pthread_create(&th[2],NULL,times,NULL); if (ret != 0) { printf("Pthread_create failed\n"); return -1; } pthread_join(th[0],NULL); pthread_join(th[1],NULL); pthread_join(th[2],NULL); return 0; }
pthread1
|----------------|post1|
pthread2
|----------------|wait1|---------------|post|
pthread2
|----------------|wait2|-----do_others---|
do_others 可以在pthread2 post 前执行业务。
Life is mess, don't let mess mess us.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了