【发布时间】:2011-08-01 13:17:46
【问题描述】:
在一段较大的代码中,我注意到 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
【问题讨论】:
标签: linux atomic glib atomic-swap