博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[国嵌攻略][088][多线程同步]
阅读量:4599 次
发布时间:2019-06-09

本文共 2516 字,大约阅读时间需要 8 分钟。

线程同步

多个线程按照规定的顺序来执行,即为线程同步。

 

threadSync1.c

#include 
#include
#include
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 
#include
#include
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);}

 

转载于:https://www.cnblogs.com/d442130165/p/5229869.html

你可能感兴趣的文章
mac os x mysql 出现./mysql: unknown variable 'sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABL 问题...
查看>>
桐桐的贸易--WA
查看>>
历届试题 高僧斗法
查看>>
linux命令系列 stat & touch
查看>>
[Tools] Webstorm Github的配置与使用
查看>>
鬼谷子绝学
查看>>
Mongodb 笔记04 特殊索引和集合、聚合、应用程序设计
查看>>
使用Post/Redirect/Get实现Asp.net防止表单重复提交
查看>>
用Html5与Asp.net MVC上传多个文件
查看>>
lambda函数,常用函数,内置函数(string,zip()map()filter())的用法
查看>>
Xcode中匹配的配置包的存放目录
查看>>
JavaScript将具有父子关系的原始数据格式化成树形结构数据(id,pid)
查看>>
CSS3.0——背景属性
查看>>
超棒的CSS3动画页面过渡效果
查看>>
【转】性能测试、负载测试、压力测试的区别
查看>>
hdu5863_dp+矩阵快速幂
查看>>
运算符
查看>>
【转载】C语言中的undefined behavior/unspecified behavior - 序
查看>>
MySQL服务使用
查看>>
C语言练手自己编写学生成绩管理系统
查看>>