锁的实现
看完上一篇文章之后,让我们来试试写一个简单的锁吧
首先我们的锁需要如下几个函数
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;
}