多线程编程

多线程编程

线程同步

互斥量

特点
  • 互斥量本质上说是一把锁,在访问共享资源前对互斥量加锁,访问完成之后解锁
  • 互斥量加锁后,其余所有尝试加锁互斥量线程都会被阻塞,而有一个互斥量解锁,那么该锁上所有的线程都会变成可运行状态
相关函数
//初始化一个互斥量
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
  • 现在互斥量够快拉
  • 不怎么用自旋锁了

屏障

特点
  • 协调多个线程并行工作的同步机制
  • 运行到同一点上停下来
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值