Reordering orders with locks

Here is some C ++ code that is accessed from multiple threads in parallel. It has a critical section:

lock.Acquire();
current_id = shared_id;
// small amounts of other code
shared_id = (shared_id + 1) % max_id;
lock.Release();
// do something with current_id

The lock variable class is the shell of the POSIX mutex implementation. Due to module operations, atomic operations cannot be used.

Is it possible that the gcc compiler with the O3 flag optimizes the code so that the current_id assignment is moved before locking?

+5
source share
2 answers

It can be compiled using O3!

The compiler will never be optimized to call a function unless the function is marked as pure using functional attributes.

, O3.

+3

​​ . , volatile, id.

+1

All Articles