c++多线程同步

线程的5种状态:

1.创建:创建线程  pthread_create;

2.就绪:资源已经准备就绪,等待cpu调度;

3.运行:cpu调度

4.阻塞:线程因为某种原因暂时被挂起,比如得不到自己需要的资源,或者获得不到互斥锁

产生死锁的四大条件缺一不可

1.互斥:任何情况下资源只能分给一个线程,若其他线程需要这块资源就需要等待,直到这块资源占有者被释放;

2.资源不可剥夺:任何一线程的资源不可被其他线程剥夺;

3.循环等待:线程在需要资源的时候,如果该资源被占用,该线程就保持循环等待的状态,直到拿到这个资源;

4.请求和保持:任何一线程,在申请资源的时候如果申请不到也不会释放自己手里的资源;

避免死锁的方法

1.资源提前分配好:提前把线程需要的资源分配好;

2.资源有序分配:将资源进行分类,对资源进行排序,按序分配;

3.分享自己的资源:如果该线程得不到资源就将该线程所占有的资源释放;

预防死锁的方法

银行家算法:1.比如老马、小马、老王来银行贷款,银行一共只有100个亿,老马贷款80亿,OK我的钱够贷给他,小马也要贷80亿(不安全),不够你先等着,老王来贷10个亿(安全),Ok够,贷给老王。

在未加锁的情况下

#include<iostream>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
using namespace std;

pthread_mutex_t mutex;
int ticket_num = 20;


void *fun1(void *args) {
    
    for (int i = 0; i < 20; ++i) {
        if (ticket_num > 0) {
            
            sleep(1); 
            cout<<"buy the "<<20 - ticket_num + 1<<"  th"<<endl;
            --ticket_num;
        }
    }
}

int main()
{
    pthread_t tids[4];
    pthread_mutex_init(&mutex, NULL);
    int flag;
    
    for (int i = 0; i < 4; ++i) {
        flag = pthread_create(&tids[i], NULL, &fun1, NULL);    

        if(flag) {

             //创建线程失败

         }

    }
    
    void *ans;
    sleep(5);
    for (int i = 0; i < 4; ++i) {
        int flag = pthread_join(tids[i], &ans);
        if (flag) {
            //等待线程结束出错
        }
        cout<<"ans = "<<ans<<endl;
    }

    return 0;
}

运行截图

线程之间运行的很乱,这就是线程未进行同步的原因,好比四个同时在12306抢票,这时余票都显示余票还有一张,四个人同时抢,都抢到了,钱也扣了,你们这时候问题来了,这张票你是给谁呢。所以要进行线程同步

1.互斥锁:

#include<iostream>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
using namespace std;

pthread_mutex_t mutex;
int ticket_num = 20;


void *fun1(void *args) {
    
    for (int i = 0; i < 20; ++i) {
        pthread_mutex_lock(&mutex);
        if (ticket_num > 0) {
            
            sleep(1); 
            cout<<"buy the "<<20 - ticket_num + 1<<"  th"<<endl;
            --ticket_num;
        }
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t tids[4];
    pthread_mutex_init(&mutex, NULL);

   // pthread_mutex_t mutex_x=PTHREAD_MUTEX_INITIALIZER;//静态初始化互斥锁
    int flag;
    
    for (int i = 0; i < 4; ++i) {
        flag = pthread_create(&tids[i], NULL, &fun1, NULL);

        if(flag) {

             //创建线程失败

         }
    }
    
    void *ans;
    //sleep(10);
    
    for (int i = 0; i < 4; ++i) {
        int flag = pthread_join(tids[i], &ans);
        if (flag) {
            //等待线程结束出错
        }
        cout<<"ans = "<<ans<<endl;
    }
    return 0;
}

2.条件变量

互斥量不是万能的,比如某个线程正在等待共享数据内某个条件出现,可可能需要重复对数据对象加锁和解锁(轮询),但是这样轮询非常耗费时间和资源,而且效率非常低,所以互斥锁不太适合这种情况

我们需要这样一种方法:当线程在等待满足某些条件时使线程进入睡眠状态,一旦条件满足,就换线因等待满足特定条件而睡眠的线程

如果我们能够实现这样一种方法,程序的效率无疑会大大提高,而这种方法正是条件变量!

#include<iostream>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
using namespace std;

pthread_mutex_t mutex;
pthread_cond_t cond;
int ticket_num = 20;

void *f1 (void* args) {
    cout<<"f1  start"<<endl;
    pthread_mutex_lock(&mutex);
    
    while (ticket_num > 10) {
        pthread_cond_wait(&cond, &mutex);
    }
    pthread_mutex_unlock(&mutex);
    cout<<"f1 end"<<endl;
}

void *f2 (void* args) {
    cout<<"f2  start"<<endl;
    pthread_mutex_lock(&mutex);
    
    ticket_num = 1;
    
    pthread_mutex_unlock(&mutex);
    
    cout<<"f2 end"<<endl;
    if (ticket_num < 10) {
        pthread_cond_signal(&cond);
    }
    

}

int main()
{
    pthread_t tids[2];
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    
    int flag;
    
    for (int i = 0; i < 1; ++i) {
        pthread_create(&tids[0], NULL, &f1, NULL);
        sleep(2);
        pthread_create(&tids[1], NULL, &f2, NULL);
    }
    
    void *ans;
    //sleep(10);
    
    for (int i = 0; i < 2; ++i) {
        int flag = pthread_join(tids[i], &ans);
        if (flag) {
            
        }
        //cout<<"ans = "<<ans<<endl;
    }
    return 0;
}

可以多个线程同时读,但是不能多个线程同时写

1.读写锁比互斥锁更加具有适用性和并行性

2.读写锁最适用于对数据结构的读操作读操作次数多余写操作次数的场合!

3.锁处于读模式时可以线程共享,而锁处于写模式时只能独占,所以读写锁又叫做共享-独占锁

4.读写锁有两种策略:强读同步和强写同步

在强读同步中,总是给读者更高的优先权,只要写者没有进行写操作,读者就可以获得访问权限

在强写同步中,总是给写者更高的优先权,读者只能等到所有正在等待或者执行的写者完成后才能进行读

不同的系统采用不同的策略,比如航班订票系统使用强写同步,图书馆查阅系统采用强读同步

根据不同的业务场景,采用不同的策略

1)初始化的销毁读写锁

静态初始化:pthread_rwlock_t rwlock=PTHREAD_RWLOCK_INITIALIZER

动态初始化:int pthread_rwlock_init(rwlock,NULL),NULL代表读写锁采用默认属性

销毁读写锁:int pthread_rwlock_destory(rwlock)

在释放某个读写锁的资源之前,需要先通过pthread_rwlock_destory函数对读写锁进行清理。释放由pthread_rwlock_init函数分配的资源

如果你想要读写锁使用非默认属性,则attr不能为NULL,得给attr赋值

int pthread_rwlockattr_init(attr),给attr初始化

int pthread_rwlockattr_destory(attr),销毁attr

2)以写的方式获取锁,以读的方式获取锁,释放读写锁

int pthread_rwlock_rdlock(rwlock),以读的方式获取锁

int pthread_rwlock_wrlock(rwlock),以写的方式获取锁

int pthread_rwlock_unlock(rwlock),释放锁

上面两个获取锁的方式都是阻塞的函数,也就是说获取不到锁的话,调用线程不是立即返回,而是阻塞执行,在需要进行写操作的时候,这种阻塞式获取锁的方式是非常不好的,你想一下,我需要进行写操作,不但没有获取到锁,我还一直在这里等待,大大拖累效率

所以我们应该采用非阻塞的方式获取锁:

int pthread_rwlock_tryrdlock(rwlock)

int pthread_rwlock_trywrlock(rwlock)

代码待更

信号量

代码待更

 

文章部分借鉴于https://www.cnblogs.com/yinbiao/p/11190336.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值