多线程编程
线程同步
互斥量
特点
- 互斥量本质上说是一把锁,在访问共享资源前对互斥量加锁,访问完成之后解锁
- 互斥量加锁后,其余所有尝试加锁互斥量线程都会被阻塞,而有一个互斥量解锁,那么该锁上所有的线程都会变成可运行状态
相关函数
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
pthread_mutex_t wirte;
pthread_mutex_t read;
int count=0;
void read()
{
lock(read);
if(count==0)
lock(wirte);
count++;
unlock(read);
lock(read)
count--;
if(count==0)
unlock(write);
unlock(read);
}
void write()
{
lock(write)
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
屏障
特点
- 协调多个线程并行工作的同步机制
- 运行到同一点上停下来