gcc原子操作与spinlock简单对比

本文通过三个测试案例:使用CAS操作、自旋锁和互斥锁实现线程同步,比较了它们在高并发场景下的性能差异。每个案例创建100个线程,每个线程递增共享变量100000次。实验结果显示,在完成相同任务的情况下,CAS操作最快,其次是自旋锁,最慢的是互斥锁。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看看测试代码

复制代码
// cas.c
#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<100000;++i){
                __sync_fetch_and_add(&count,1);
        }
        return NULL;
}

int main(int argc, const char *argv[])
{
        pthread_t id[100];
        int i = 0;

        for(i=0;i<100;++i){
                pthread_create(&id[i],NULL,test_func,NULL);
        }

        for(i=0;i<100;++i){
                pthread_join(id[i],NULL);
        }

        printf("%d\n",count);
        return 0;
}
复制代码
复制代码
// spinlock.c
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

static int count = 0;
static pthread_spinlock_t spinlock;

void *test_func(void *arg)
{
        int i=0;
        for(i=0;i<100000;++i){
                pthread_spin_lock (&spinlock);
                count++;
                pthread_spin_unlock(&spinlock);
        }
        return NULL;
}

int main(int argc, const char *argv[])
{
        pthread_t id[100];
        int i = 0;
        pthread_spin_init (&spinlock, 0);

        for(i=0;i<100;++i){
                pthread_create(&id[i],NULL,test_func,NULL);
        }

        for(i=0;i<100;++i){
                pthread_join(id[i],NULL);
        }

        printf("%d\n",count);
        return 0;
}
复制代码
复制代码
// mutex.c 
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

static int count = 0;
static pthread_mutex_t mutex;

void *test_func(void *arg)
{
        int i=0;
        for(i=0;i<100000;++i){
                pthread_mutex_lock (&mutex);
                count++;
                pthread_mutex_unlock(&mutex);
        }
        return NULL;
}

int main(int argc, const char *argv[])
{
        pthread_t id[100];
        int i = 0;
        pthread_mutex_init (&mutex,NULL);

        for(i=0;i<100;++i){
                pthread_create(&id[i],NULL,test_func,NULL);
        }

        for(i=0;i<100;++i){
                pthread_join(id[i],NULL);
        }

        printf("%d\n",count);
        return 0;
}
复制代码

 

 

结果:

复制代码
# time ./mutex                            
10000000
real    0m0.235s
user    0m0.040s
sys     0m0.000s

# time ./spinlock 
10000000
real    0m0.111s
user    0m0.010s
sys     0m0.010s

# time ./cas 
10000000
real    0m0.083s
user    0m0.010s
sys     0m0.000s


本文转自feisky博客园博客,原文链接:http://www.cnblogs.com/feisky/archive/2012/07/29/2613921.html,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值