Is it safe to spin on volatile on user mode threads?

I'm not entirely sure how safe it is to spin on a volatile variable in user mode threads to implement a lightweight spin block, I looked at the tbb source code, tbb_machine.h: 170.

//! Spin WHILE the value of the variable is equal to a given value
/** T and U should be comparable types. */
template<typename T, typename U>
void spin_wait_while_eq( const volatile T& location, U value ) {
    atomic_backoff backoff;
    while( location==value ) backoff.pause();
}

      

And there are no fences in the atomic_backoff class as I can see. Whereas from another spin_lock custom mode implementation most of them use CAS (Compare and Swap).

+2


a source to share


2 answers


Tricky. I would say that in theory this code is unsafe. If there are no memory barriers, access to the data you are guarding can be traversed through a spinlock. However, this could only be done if the compiler was very aggressive and could see the purpose in this reordering.

Perhaps Intel simply determined that this code works on all modern compilers, and that while the compiler could theoretically perform conversions that would break this code, those conversions would not speed up the program, and therefore compilers probably won't. ...



Another possibility is that this code is only used by compilers that implicitly implement memory barriers around calls volatile

. The Microsoft Visual C ++ Compiler (2005 and later) does this. Have you checked if this is finalized into a block #ifdef

or similar by only applying this implementation on compilers that volatile

use memory barriers?

+2


a source


Note that this is a rotation wait, not a rotation lock. There is no write operation. Received nothing.



If you tried to add a write operation to complete the blocking process, you have an unresolved race.

0


a source







All Articles