2

I'm doing inter-process communication using shared memory on a multi-processor server. I've simplified the code to the following:

struct MyStruct {
  uint64_t x;
};

volatile MyStruct* my_struct;  // initialized elsewhere

void MyFunction(uint64_t y) {
   while (true) {
      uint64_t current_x = my_struct->x;
      if (__sync_bool_compare_and_swap(&my_struct->x, current_x, y)) {
         DoWork(current_x, y);  // do work here depending on current_x and y
         return;
      }
   }
}

My question: is this code correct?

In particular, do I need to add a

__sync_synchronize()

before the line

uint64_t current_x = my_struct->x or will that be redundant since the atomic CAS on the following line effectively does that anyways? As you can see, what effectively I want is the __sync_lock_test_and_set functionality. However, from http://gcc.gnu.org/onlinedocs/gcc-4.1.1/gcc/Atomic-Builtins.html it looks like that function may not work always as expected.

4

1 回答 1

0
   while (true) {
      uint64_t current_x = my_struct->x;
      /* CAVEAT: my_struct may point to something different now */
      if (__sync_bool_compare_and_swap(&my_struct->x, current_x, y)) {

如果您不关心它my_struct可能指向不同的结构,但具有与x原始结构相同的值,那么代码看起来不错。您的代码似乎暗示它没问题,因为您DoWork只关心current_xand y

于 2012-07-10T02:15:56.137 回答