Linux多线程同步方式总结
2017-11-19 20:37
417 查看
线程同步方式的逻辑
互斥锁
条件变量
读写锁
cond_wait :
1. 释放互斥锁mu,使得其他线程能够访问,
2. 同时等待,直到cond的通知。这样符合条件的线程就开始等待。
3. 接收道通知之后,cond_wait到unlock部分重新被上锁,接收到通知的线程依次执行。
[b]cond_broadcast:
1. 负责给所有调用cond_wait的线程发送通知,以便让那些线程恢复运行。
共享读取锁 (shared-read)
互斥写入锁 (exclusive-write lock)
打开(unlock)
如果一个线程获得R锁,其他线程也可以获取R锁,但是如果此时,有线程想要获得W锁,需要等待所有获得R锁的线程释放
如果一个线程获得了W锁,其他线程必须等它释放才能获得R或者W锁
读写锁使得读操作可以共享,写操作被保护
互斥锁
条件变量
读写锁
线程同步方式的逻辑
互斥锁
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部分重新被上锁,接收到通知的线程依次执行。
[b]cond_broadcast:
1. 负责给所有调用cond_wait的线程发送通知,以便让那些线程恢复运行。
读写锁
与互斥锁类似;共有三种状态:共享读取锁 (shared-read)
互斥写入锁 (exclusive-write lock)
打开(unlock)
如果一个线程获得R锁,其他线程也可以获取R锁,但是如果此时,有线程想要获得W锁,需要等待所有获得R锁的线程释放
如果一个线程获得了W锁,其他线程必须等它释放才能获得R或者W锁
读写锁使得读操作可以共享,写操作被保护
相关文章推荐
- .net 多线程同步方式总结
- windows与linux之间文件的传输方式总结
- Linux线程退出方式总结
- Windows与Vmware下的Linux文件共享方式总结
- Linux的进程/线程间通信方式总结 04
- 多进程间通信方式和多线程同步机制总结
- Linux 平台MySQL启动关闭方式总结
- linux 多线程同步方式
- Linux的进程/线程间通信方式总结
- 《Linux0.11内核完全注释》读书笔记之内核启动方式总结
- linux 安装软件包方式总结
- Windows与Vmware下的Linux文件共享方式总结
- Linux学习之——登录方式总结
- Linux的进程/线程通信方式总结
- Linux进程间通信的几种方式总结-概述
- Linux多线程同步方式
- Linux下多线程同步方式之互斥量,信号量,条件变量
- Linux的进程/线程间通信方式总结
- linux内核剖析(七)Linux进程间通信的几种方式总结
- Linux进程间通信的几种方式总结