Linux多线程同步方式总结
来源:互联网 发布:电信软件下载 编辑:程序博客网 时间:2024/06/12 11:04
- 线程同步方式的逻辑
- 互斥锁
- 条件变量
- 读写锁
线程同步方式的逻辑
互斥锁
lock\unlock,这样就可以构成一个原子操作
/*mu is a global mutex*/while (1) { /*infinite loop*/ mutex_lock(mu); /*aquire mutex and lock it, if cannot, wait until mutex is unblocked*/ if (i != 0) i = i - 1; else { printf("no more tickets"); exit(); } mutex_unlock(mu); /*release mutex, make it unblocked*/}
条件变量
经常保存为全局变量,并和互斥锁合作。
/*mu: global mutex, cond: global codition variable, num: global int*/mutex_lock(mu)num = num + 1; /*worker build the room*/if (num <= 10) { /*worker is within the first 10 to finish*/ cond_wait(mu, cond); /*wait*/ printf("drink beer");}else if (num = 11) { /*workder is the 11th to finish*/ cond_broadcast(mu, cond); /*inform the other 9 to wake up*/}mutex_unlock(mu);
cond_wait :
1. 释放互斥锁mu,使得其他线程能够访问,
2. 同时等待,直到cond的通知。这样符合条件的线程就开始等待。
3. 接收道通知之后,cond_wait到unlock部分重新被上锁,接收到通知的线程依次执行。
cond_broadcast:
1. 负责给所有调用cond_wait的线程发送通知,以便让那些线程恢复运行。
读写锁
- 与互斥锁类似;共有三种状态:
- 共享读取锁 (shared-read)
- 互斥写入锁 (exclusive-write lock)
- 打开(unlock)
- 如果一个线程获得R锁,其他线程也可以获取R锁,但是如果此时,有线程想要获得W锁,需要等待所有获得R锁的线程释放
- 如果一个线程获得了W锁,其他线程必须等它释放才能获得R或者W锁
- 读写锁使得读操作可以共享,写操作被保护
阅读全文
0 0
- Linux多线程同步方式总结
- linux 多线程同步方式
- Linux多线程同步方式
- linux多线程同步方式
- .net 多线程同步方式总结
- linux进程同步方式总结
- Linux内核同步方式总结
- Linux多线程同步的几种方式
- Linux中的常用多线程同步方式
- Linux多线程同步的几种方式
- Linux Pthread 多线程典型同步方式
- Linux多线程同步的几种方式
- Linux中的常用多线程同步方式
- Linux多线程同步的几种方式
- Linux多线程同步的几种方式
- Linux多线程同步的几种方式
- Linux多线程同步的几种方式
- Linux多线程同步的几种方式
- Linux中模拟shell实现mybash
- MVC三层架构
- 二级列表购物车
- 文章标题
- Hello World!
- Linux多线程同步方式总结
- Bochs调试内核
- 2017.11.19
- 二叉树及其四种遍历
- HTML5游戏设计与制作
- 图的邻接矩阵表示
- AJAX跨越、JS跨越请求 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin
- MyBatis HelloWorld
- 数据库相关概念解析