gcc 利用原子操作实现自旋锁

2018-01-12  本文已影响0人  水果糖的小铺子

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个问题:

上一篇 下一篇

猜你喜欢

热点阅读