linux无锁化编程

         muduo库中使用了几个linux无锁编程接口,这些函数在多线程下操作时无需加锁也能实现原子操作,而且加锁会影响性能。
__sync_val_compare_and_swap(type *ptr, type oldval,  type newval, ...)   如果*ptr == oldval,就将newval写入*ptr
__sync_fetch_and_add( &global_int, 1)   先fetch(获得),然后自加,返回的是自加以前的值
__sync_lock_test_and_set(type *ptr, type value, ...)    将*ptr设为value并返回*ptr操作之前的值

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
 
int sum = 0;

/*void* adder1(void *p)
{
    for(int i = 0; i < 1000000; i++)  // 百万次
    {
        sum++;
    }
 
    return NULL;
}*/
 
/*void* adder2(void *p)
{
    int old = sum;
    for(int i = 0; i < 1000000; i++)  // 百万次
    {
        while(!__sync_bool_compare_and_swap(&sum, old, old + 1))  // 如果old等于sum, 就把old+1写入sum
        {
           old = sum; // 更新old
        }
    }
 
    return NULL;
}*/

void* adder3(void *p)
{
    for(int i = 0; i < 1000000; i++)  // 百万次
    {
        __sync_fetch_and_add(&sum,1);      
    }
 
    return NULL;
}

int main()
{
    pthread_t threads[10];
    for(int i = 0;i < 10; i++)
    {
        pthread_create(&threads[i], NULL, adder3, NULL);
    }
	
    for(int i = 0; i < 10; i++)
    {
        pthread_join(threads[i], NULL);
    }
 
    printf("sum is %d\n",sum);

    return 0;
}

addr1结果不是我们预期的,addr2和addr3是我们预期的(10000000),编译要加上选项-lpthread -march=nocona -mtune=generic

 

参考地址:https://blog.csdn.net/stpeace/article/details/81150393

                  https://blog.csdn.net/hzhsan/article/details/25124901

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盼盼编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值