3
在更大的一段代碼,我注意到g_atomic_ *在glib函數沒有做什麼我的預期,所以我寫了這個簡單的例子:GLIB:g_atomic_int_get變爲NO-OP?
#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);
}
}
當我編譯這與海灣合作委員會的「-E」選項(預處理後停止),我注意到調用g_atomic_int_get(&富)已經成爲:
(*(&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
有趣的是你有沒有需要內存屏障的任何文檔(uname -a給出了「Linux rhel-5.4-dev 2.6.18-164.15.1.el5xen#1 SMP Mon Mar 1 11:11: 42 EST 2010 x86_64 x86_64 x86_64 GNU/Linux「在我的系統上)。我沒有意識到有任何這樣的架構是真實的,所以我想多做一些閱讀。 – laslowh 2011-04-09 21:24:50