Compiler/Hardware optimizations of code and relaxed atomics

50 views Asked by At

I've been listening to Herb Sutter's Atomic Weapons talk and there's a slide where he discusses released atomic variables and optimizations on code. My question has more to do with what compiler optimizations are allowed to do and what they are not. Memory_order_relaxed is this magic that allows atomic operations to float about inside the function they are used in.

Consider the following snippet (count is an atomic variable) (assume that all uses of count have been shown)-

//threaded function
// function start
...
while(...)
{
    ...
    if(...)
         ++count.fetch_add(1,memory_order_relaxed);
    ...
}
...
// function end
//main thread
int main()
{
   launch_threads();

   join_threads()
   cout<<count.load(memory_order_relaxed);
}

Specifically, in the thread function, count is allowed to be moved anywhere in the function. In this context, please clarify if my assumptions are right-

  1. Logically, this means that the if(...) should also move along with it and hence the conditional can be placed anywhere within the while(...).
  2. Since the while(...) contains the relaxed variable, it should be able to move up and down inside the function block with no restrictions.
  3. Can the count variable be moved out of the if(...)/while(...) and be replaced with a register of some sort?

If there are any links that can help me better understand the scope of compiler optimizations, do add them.

0

There are 0 answers