GLIB: g_atomic_int_get becomes NO-OP?

£可爱£侵袭症+ 提交于 2020-01-02 08:24:25

问题


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);
  }
}

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))

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

回答1:


The architecture you are on does not require a memory barrier for atomic integer set/get operations, so the transformation is valid.

Here's where it's defined: 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.



来源:https://stackoverflow.com/questions/5596129/glib-g-atomic-int-get-becomes-no-op

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!