锁的实现(自旋锁)

锁的实现

看完上一篇文章之后,让我们来试试写一个简单的锁吧

首先我们的锁需要如下几个函数

mythread_init(mythread_t m)
mythread_lock(mythread_t m)
mythread_unlock(mythread_t m)

很简单很容易想到吧

下面就是我们的实现

void mythread_init(mythread_t m)
{
    m.mlock=0;//0代表没锁,1代表锁上了
}
void mythread_lock(mythread_t* m)
{
    while(m->mlock==1);//如果已经被锁上了,就while循环等待

    m->mlock=1;//如果没锁就锁上
}
void mythread_unlock(mythread_t* m)
{
    m->mlock=0;//释放锁
}

让我们来试试它的效果怎么样吧

#include<iostream>
#include<pthread.h>
typedef struct mythread{
int mlock;
}mythread_t;

void mythread_init(mythread_t m)
{
    m.mlock=0;//0代表没锁,1代表锁上了
}
void mythread_lock(mythread_t* m)
{
    while(m->mlock==1);
    m->mlock=1;
}
void mythread_unlock(mythread_t* m)
{
    m->mlock=0;
}

int counter=0;
mythread_t m;
int n=50;
void *child(void *arg){
    for(int i=0;i<n;i++)//试着修改n的值,看看会发生什么
    {
        mythread_lock(&m);
        counter++;
        mythread_unlock(&m);
    }
    return 0;
}

int main(){
    mythread_init(m);
    pthread_t p1;
    pthread_t p2;
    pthread_create(&p1,NULL,child,NULL);
    pthread_create(&p2,NULL,child,NULL);
    pthread_join(p1,NULL);
    pthread_join(p2,NULL);
    std::cout<<"counter="<<counter<<std::endl;
}

试着修改n的值,看看会发生什么,事实证明,我们失败了,当n的值较小时,锁还能有用,但是当n的值变大时,我们的锁就彻底失效了。

让我们来思考一下为什么会发生这种事情呢。

原因:当线程1进入while判断时,此时m->mlock=0。不用等待,但是此时切换线程,线程2也进入while判断,此时m->mlock还是0(线程1尚未来得及修改),此时相当于并没有拦截住线程2,因此我们的锁失败了。参考下图,取自《操作系统导论》,非常推荐大家去阅读。flag就是本代码中的m.mlcok
在这里插入图片描述

现在我们要怎么样才能完成互斥呢。
我们需要在while判断之前就完成就把m.mlock设置为1,还得让它判断修改之前的值。此时就需要用到这样一个函数

int test_set(int* ptr,int new){
    int old=*ptr;
    *ptr=new;
    return old;
}

这个函数可以理解为伪代码,因为实际中该函数应该为原子性的,是由硬件实现的
把m.mlock的值保存到一个old里面,再赋一个新值给m.mlcok,最后返回旧的值,这样就能保证判断旧的值,而且判断结束之前,就已经修改了这个值
修改mythread_lock函数

void mythread_lock(mythread_t* m)
{
    while(test_set(&m->mlock,1)==1);
}
#include<iostream>
#include<pthread.h>
typedef struct mythread{
int mlock;
}mythread_t;
void mythread_init(mythread_t* m)
{
    m->mlock=0;//0代表没锁,1代表锁上了
}
int test_set(int* ptr,int x){
    int old=*ptr;
    *ptr=x;
    return old;
}

void mythread_lock(mythread_t* m)
{
    while(test_set(&m->mlock,1)==1);

}
void mythread_unlock(mythread_t* m)
{

    m->mlock=0;
}

int counter=0;
mythread_t m;

void *child(void *arg){
    for(int i=0;i<50000;i++)
    {
        mythread_lock(&m);
        counter++;
        mythread_unlock(&m);
    }
    return 0;
}

int main(){
    mythread_init(&m);
    pthread_t p1;
    pthread_t p2;
    pthread_create(&p1,NULL,child,NULL);
    pthread_create(&p2,NULL,child,NULL);
    pthread_join(p1,NULL);
    pthread_join(p2,NULL);
    std::cout<<"counter="<<counter<<std::endl;
}

自旋锁的实现有很多种方式,我只是简单写了其中一种。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zxx147

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值