Fence example

suggest change

A producer and a consumer can be coordinated with fences and relaxed atomic operations:

int x, y;
std::atomic<bool> ready{false};

void init()
{
  x = 2;
  y = 3;
  std::atomic_thread_fence(std::memory_order_release);
  ready.store(true, std::memory_order_relaxed);
}
void use()
{
  if (ready.load(std::memory_order_relaxed))
  {
    std::atomic_thread_fence(std::memory_order_acquire);
    std::cout << x + y;
  }
}

If the relaxed load reads the value written by the relaxed store, the release fence synchronizes with the acquire fence. Writes to x and y that are sequenced before the release fence then happen before the std::cout statement that is sequenced after the acquire fence. A relaxed load and store do not create that happens-before relationship by themselves.

A fence might be beneficial if it can reduce the overall number of acquire, release or other synchronization operations. For example:

void block_and_use()
{
  while (!ready.load(std::memory_order_relaxed))
    ;
  std::atomic_thread_fence(std::memory_order_acquire);
  std::cout << x + y;
}

The block_and_use() function spins until the ready flag is set with the help of relaxed atomic load. Then a single acquire fence is used to provide the needed memory ordering.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents