x86下的原子操作实现

来源:互联网 发布:网络新媒体专业 编辑:程序博客网 时间:2024/05/01 01:54

1.gnu lib提供原子操作的实现

#include <stdio.h>#include <pthread.h>#include <stdlib.h>static int count = 0;void *test_func(void *arg){        int i=0;        for(i=0;i<20000;++i){//                __sync_fetch_and_add(&count,1);                count ++;        }        return NULL;}int main(int argc, const char *argv[]){        pthread_t id[20];        int i = 0;        for(i=0;i<20;++i){                pthread_create(&id[i],NULL,test_func,NULL);        }        for(i=0;i<20;++i){                pthread_join(id[i],NULL);        }        printf("%d\n",count);        return 0;}
2.利用汇编自己实现

#include <stdio.h>#include <pthread.h>#include <stdlib.h>#define LOCK "lock ; "typedef struct { volatile int counter; } atomic_t;static __inline__ void atomic_inc(atomic_t *v){    __asm__ __volatile__(       LOCK "incl %0"       :"=m" (v->counter)       :"m" (v->counter));}static atomic_t count = {0};void *test_func(void *arg){        int i=0;        for(i=0;i<20000;++i){                atomic_inc(&count);        }        return NULL;}int main(int argc, const char *argv[]){        pthread_t id[20];        int i = 0;        for(i=0;i<20;++i){                pthread_create(&id[i],NULL,test_func,NULL);        }        for(i=0;i<20;++i){                pthread_join(id[i],NULL);        }        printf("%d\n",count.counter);        return 0;}


0 0
原创粉丝点击