GLIB:g_atomic_int_get变成NO-OP吗? [英] GLIB: g_atomic_int_get becomes NO-OP?
问题描述
在较大的一段代码中,我注意到glib中的g_atomic_ *函数没有达到我的预期,所以我写了这个简单的示例:
In a larger piece of code, I noticed that the g_atomic_* functions in glib were not doing what I expected, so I wrote this simple example:
#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)的调用已变为:
When I compile this with GCC's '-E' option (stop after pre-processing), I notice that the call to g_atomic_int_get(&foo) has become:
(*(&foo))
和g_atomic_int_set((((int *)ptr),42)已变为:
and g_atomic_int_set(((int*)ptr), 42) has become:
((void) (*(((int*)ptr)) = (42)))
很明显,我期待一些原子比较和交换操作,而不仅仅是简单的(线程不安全)分配.我在做什么错了?
Clearly I was expecting some atomic compare and swap operations, not just simple (thread-unsafe) assignments. What am I doing wrong?
作为参考,我的编译命令如下:
For reference my compile command looks like this:
gcc -m64 -E -o foo.E `pkg-config --cflags glib-2.0` -O0 -g foo.c
推荐答案
您所使用的体系结构不需要原子整数set/get操作的内存屏障,因此转换有效.
The architecture you are on does not require a memory barrier for atomic integer set/get operations, so the transformation is valid.
在此定义: http://git.gnome .org/browse/glib/tree/glib/gatomic.h#n60
这是一件好事,因为否则您需要为每个原子操作锁定全局互斥锁.
This is a good thing, because otherwise you'd need to lock a global mutex for every atomic operation.
这篇关于GLIB:g_atomic_int_get变成NO-OP吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!