[英]gcc AtomicBuiltins strange behavior in gcc 4.1.1
在 gcc doc 链接gcc-doc我看到 gcc 版本 4.1.1 具有原子内置函数。
在我的项目中,我们在centos5.0中使用gcc 4.1.1,然后编译后我们的项目在centos5.0之后运行良好。 这是我的测试代码。
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdbool.h>
static int count = 0;
void *test_func(void *arg)
{
int i=0;
int result = 0;
for(i=0;i<2000;++i)
{
__sync_add_and_fetch(&count,1);
}
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_t id[10];
int i = 0;
for(i=0;i<10;++i){
pthread_create(&id[i],NULL,test_func,NULL);
}
for(i=0;i<10;++i){
pthread_join(id[i],NULL);
}
//10*2000=20000
printf("%u\n",count);
return 0;
}
当我将功能更改为以下内容时:
void *test_func(void *arg)
{
int i=0;
int result = 0;
for(i=0;i<2000;++i)
{
result = __sync_add_and_fetch(&count,1);
}
return NULL;
}
gcc -g -o code code.c -lpthread
然后编译出错了:undefined reference to `__sync_add_and_fetch_4' 我不知道为什么会出错。
现在我想使用函数:__sync_val_compare_and_swap,这是来自stackoverflow的演示
#include <stdio.h>
#include <inttypes.h>
#include <pthread.h>
#include <stdbool.h>
#include <assert.h>
volatile bool lock;
void *locktest( void *arg )
{
int i = 0;
for ( i = 0 ; i < 100000 ; ++i )
{
// acquire a lock
while( __sync_val_compare_and_swap( &lock, false, true ) == true )
{
// Spin while we don't acquire
}
// make sure we have the lock
assert( lock == true );
// release the lock
assert( __sync_val_compare_and_swap( &lock, true, false ) == true );
}
}
int main (void)
{
return 0;
}
这是错误的编译:/root/library/demo/sync_val_compare.c:14: undefined reference to __sync_val_compare_and_swap_1' /root/library/demo/sync_val_compare.c:23: undefined reference to
__sync_val_compare_and_swap_1'
我不知道为什么?我理解错了吗?
如果目标架构无法支持特定的__sync
函数,GCC 会将其视为外部函数(以防您想提供实现)。 如果这样做,它会附加元素大小; 这就是4
的来源。 您选择的目标架构似乎不支持 4 字节类型的原子add_and_fetch
(这让我怀疑它根本不支持原子内在函数)。 使用-march
编译器选项强制特定架构可能会有所帮助; 试试-march=native
看看是否足够。
顺便说一句,对于支持它们的 GCC 版本,您应该使用__atomic
内部函数而不是__sync
内部函数。 __atomic
内在函数使您可以更好地控制内存顺序保证,从而可能提高性能。 (不过,当您尝试在不支持它们的架构上使用它们时,两组内在函数都表现出相同的问题。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.