在一段较大的代码中,我注意到glib中的g_atomic_*函数没有完成我预期的工作,因此我编写了这个简单的示例:
#include <stdlib.h>
#include "glib.h"
#include "pthread.h"
#include "stdio.h"
void *set_foo(void *ptr) {
g_atomic_int_set(((int*)ptr), 42);
return NULL;
}
int main(void) {
int foo = 0;
pthread_t other;
if (pthread_create(&other, NULL, set_foo, &foo)== 0) {
pthread_join(other, NULL);
printf("Got %d\n", g_atomic_int_get(&foo));
} else {
printf("Thread did not run\n");
exit(1);
}
}当我用GCC的'-E‘选项(预处理后停止)编译它时,我注意到对g_atomic_int_get(&foo)的调用变成了:
(*(&foo))而g_atomic_int_set(int*)ptr),42)变成了:
((void) (*(((int*)ptr)) = (42)))显然,我期望的是一些原子比较和交换操作,而不仅仅是简单的(线程不安全的)分配。我做错了什么?
作为参考,我的编译命令如下所示:
gcc -m64 -E -o foo.E `pkg-config --cflags glib-2.0` -O0 -g foo.c发布于 2011-04-09 05:06:50
您所在的体系结构不需要用于原子整数设置/获取操作的内存屏障,因此转换是有效的。
下面是它的定义位置:http://git.gnome.org/browse/glib/tree/glib/gatomic.h#n60
这是一件好事,因为否则您将需要为每个原子操作执行lock a global mutex。
https://stackoverflow.com/questions/5596129
复制相似问题