[PATCH] microoptimize by trying to avoid locking a locked mutex

David Chisnall theraven at FreeBSD.org
Fri Nov 6 12:21:48 UTC 2015


On 5 Nov 2015, at 16:55, Mateusz Guzik <mjguzik at gmail.com> wrote:
> 
>> Will that cause problems, especially for code inside a loop
>> where the compiler may decide to shuffle things around?
>> 
> 
> Lock value is volatile, so the compiler should not screw us up.

Note: volatile means do not reorder loads/stores *to this value*, the compiler is completely free to reorder loads/stores to other values around this one.  _Atomic exists in C11 to do the right thing when you want to enforce stricter barriers.  In this case, we’re currently relying on the compiler not being able to see through the assembly.

At some point in the future, I imagine that we’ll move to using C11 atomic operations, which will allow the compiler more freedom.  The new reads that you’re currently doing should be replaced by explicit atomic reads with a relaxed memory order (to enforce atomicity with respect to that variable).  If we were to replace the mtx_lock field with an _Atomic variant, then the current code would make it a sequentially consistent read, which would add a lot of extra overhead.  Note also that it is undefined behaviour in C11 to do atomic and non-atomic accesses to the same underlying memory location.  Please consider the future maintainability of the code when making this change.

David



More information about the freebsd-current mailing list