[国嵌攻略][088][多线程同步]
线程同步
多个线程按照规定的顺序来执行,即为线程同步。
threadSync1.c
#include <pthread.h> #include <stdio.h> #include <unistd.h> pthread_mutex_t mutex; int task = 0; void *thread0(); void *thread1(); void main(){ //创建互斥锁 pthread_mutex_init(&mutex, NULL); //创建子线程 pthread_t thread[2]; pthread_create(&thread[0], NULL, thread0, NULL); pthread_create(&thread[1], NULL, thread1, NULL); //等待子线程 pthread_join(thread[0], NULL); pthread_join(thread[1], NULL); } void *thread0(){ //处理任务 int i; for(i = 0; i < 10; i++){ //获取互斥锁 pthread_mutex_lock(&mutex); //处理任务 task++; printf("thread0 task:%d\n", task); //释放互斥锁 pthread_mutex_unlock(&mutex); //睡眠等待 sleep(1); } //退出线程 pthread_exit(NULL); } void *thread1(){ //获取互斥锁 pthread_mutex_lock(&mutex); //查看任务 while(task != 10){ //释放互斥锁 pthread_mutex_unlock(&mutex); //睡眠等待 sleep(1); //获取互斥锁 pthread_mutex_lock(&mutex); } //处理任务 task++; printf("thread1 task:%d\n", task); //释放互斥锁 pthread_mutex_unlock(&mutex); //退出线程 pthread_exit(NULL); }
threadSync2.c
#include <pthread.h> #include <stdio.h> #include <unistd.h> pthread_mutex_t mutex; //互斥锁 pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //条件变量 int task = 0; void *thread0(); void *thread1(); void main(){ //创建互斥锁 pthread_mutex_init(&mutex, NULL); //创建子线程 pthread_t thread[2]; pthread_create(&thread[0], NULL, thread0, NULL); pthread_create(&thread[1], NULL, thread1, NULL); //等待子线程 pthread_join(thread[0], NULL); pthread_join(thread[1], NULL); } void *thread0(){ //处理任务 int i; for(i = 0; i < 10; i++){ //获取互斥锁 pthread_mutex_lock(&mutex); //处理任务 task++; printf("thread0 task:%d\n", task); //释放互斥锁 pthread_mutex_unlock(&mutex); //睡眠等待 sleep(1); } //条件通知 pthread_cond_signal(&cond); //退出线程 pthread_exit(NULL); } void *thread1(){ //获取互斥锁 pthread_mutex_lock(&mutex); //条件等待 if(task != 10){ pthread_cond_wait(&cond, &mutex); //条件等待时会自动解锁,然后睡眠等待,获得条件通知再自动加锁 } //处理任务 task++; printf("thread1 task:%d\n", task); //释放互斥锁 pthread_mutex_unlock(&mutex); //退出线程 pthread_exit(NULL); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术