IMHO atomic::load/store example is not correct

Look at code at http://www.cplusplus.com/reference/atomic/atomic/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>       // std::cout
#include <atomic>         // std::atomic, std::memory_order_relaxed
#include <thread>         // std::thread

std::atomic<int> foo (0);

void set_foo(int x) {
  foo.store(x,std::memory_order_relaxed);     // set value atomically
}

void print_foo() {
  int x;
  do {
    x = foo.load(std::memory_order_relaxed);  // get value atomically
  } while (x==0);
  std::cout << "foo: " << x << '\n';
}

int main ()
{
  std::thread first (print_foo);
  std::thread second (set_foo,10);
  first.join();
  second.join();
  return 0;
}

First thread calls print_foo(). It allocates int x in it's stack frame (variable 1). Then it waits for x != 0.
Second thread calls set_foo(). Argument integer 10 (variable 2) pushed into stack frame of set_foo(). Moreover, it's pushed in stack of other frame.
So variable 1 and variable 2 are at different places. set_foo() can't change variable of print_foo().
set_foo() can't change variable of print_foo().
Yes, it cannot. But it can change value of foo, which then loaded in print_foo().

Oops! You are right. I'm mistaked.
Topic archived. No new replies allowed.