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
参考地址: