lock.h文件
typedef struct spin_lock{
int lock;
}Lock;
#define __Lock(Lock) do{\
if(__sync_lock_test_and_set(&(&Lock)->lock,1))\
continue;
#define __UnLock(Lock) \
__sync_lock_release(&(&Lock)->lock,0);\
}while(0)
//初始化锁
static inline
void init(Lock* L){
L->lock = 0;
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "lock.h"
#include <pthread.h>
#define MaxThread 4
static long count = 0;
Lock global_Lock;
void* work(){
while(1){
if(count>100)
break;
__Lock(global_Lock);
printf("线程:%lu为count执行自加操作。\n",(long)pthread_self());
++count;
__UnLock(global_Lock);
}
pthread_exit("thread exit...\n");;
}
int main(int argc, char const *argv[])
{
init(&global_Lock);
pthread_t p[MaxThread];
for(int i=0;i<MaxThread;i++){
int status = pthread_create(&p[i],NULL,work,NULL);
status != 0 ?exit(-1):pthread_detach(p[i]);
}
pthread_exit("Main thread exit...\n");
return 0;
}
先回答2个问题:
-
为什么锁的实现用宏来写?
答:不是因为速度快,也不是因为内联! 而是因为两者成对出现!否则替换和编译期间就会出错。
-
2、为什么不提供trylock?
答:自旋锁都在user space,再非手动切换切换线程调度的情况下不需要用户主动重试。