多线程编程
来源:互联网 发布:vb中动态数组ppt 编辑:程序博客网 时间:2024/05/14 19:08
多线程编程
线程同步
互斥量
特点
- 互斥量本质上说是一把锁,在访问共享资源前对互斥量加锁,访问完成之后解锁
- 互斥量加锁后,其余所有尝试加锁互斥量线程都会被阻塞,而有一个互斥量解锁,那么该锁上所有的线程都会变成可运行状态
相关函数
//初始化一个互斥量int pthread_mutex_init(pthread_mutex_t *restrict mutexm ,const pthread_mutexattr_t * restrict attr);//注销一个互斥量int pthread_mutex_destroy(pthread_mutex_t * mutex);//给互斥量加锁int pthread_mutex_lock(pthread_mutex_t *);//给互斥量解锁int pthread_mutex_unlock(pthread_mutex_t *);//尝试给互斥量解锁(解锁失败并不会阻塞线程)int pthread_mutex_trylock(phtread_mutex_t *);
Tip
- 注意两个线程分别以A,B和B,A的顺序加锁的时候,可能会发生死锁,要注意
读写锁
特点
- 读写锁有三种状态,读模式下加锁,写模式下加锁,不加锁状态
- 类似于PV模型中的读者写者模型吧
相关函数
#include<pthread.h>//读写锁初始化int pthread_rwlock_init(pthread_rwlock_t *restrict , const pthread_rwlockattr_t * restrict attr);//注销读写锁int pthread_rwlock_destory(pthread_rwlock_t *rwlock);//读加锁int pthread_rwlock_rdlock(pthread_rwlock_t *);//写加锁int pthread_rwlock_wrlock(pthread_rwlock_t *);//解锁int pthread_rwlock_unlock(pthread_rwlock_t *)
Tips
//读写锁可以用mutex实现pthread_mutex_t wirte;pthread_mutex_t read;int count=0;void read(){ lock(read); if(count==0) lock(wirte); count++; unlock(read); //do some read lock(read) count--; if(count==0) unlock(write); unlock(read);}void write(){ lock(write) //do something wirte unlock(write)}
条件变量
特点
- 条件变量,结合互斥量,允许线程以无竞争的方式等待的条件发生
相关函数
#include<pthread.h>//初始化int pthread_cond_init(pthread_cond_t *restrict cond,const pthread_condattr_t * restrict attr);//注销int pthread_cond_destroy(pthread_cond_t * cond);//等待条件int pthread_cond_wait(pthread_cond_t* restrict cond,pthread_mutex_t * restrict mutex);//对一个以上发出信号int pthread_cond_signal(pthread_cond_t * );//唤醒所有的线程int pthread_cond_broadcast(phtread_cond_t *);
自旋锁
特点
- 与互斥量类似,但是他不阻塞线程,而是处于忙等状态,比较适合于锁持有时间较短,而且线程不希望在重新调度上花太多的成本
相关函数
#include<pthread.h>//初始化自旋锁int pthread_spin_init(pthread_spinlock_t *lock,int pshared);//注销自旋锁int pthread_spin_destory(pthread_spinlock_t *lock).....
TIPS
- 现在互斥量够快拉
- 不怎么用自旋锁了
屏障
特点
- 协调多个线程并行工作的同步机制
- 运行到同一点上停下来
0 0
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- 多线程编程
- Maven学习-继承
- Hibernate占位符问题[use named parameters or JPA-style positional parameters instead.]
- Android调色板的开发与RGB颜色的使用
- 两个队列实现一个栈——栈和队列面试题(3)
- 基础控件
- 多线程编程
- Android事件分发传递回传机制详解
- centos7上部署php+mysql+nginx
- Liunx常用指令整理-1
- 漫步线性代数二十二——行列式性质
- 操作系统
- js--new操作符
- Android ListView
- React学习笔记—虚拟DOM