[libdispatch-dev] lib dispatch worker threads may loop depending on compiler optimization

Daniel A. Steffen dsteffen at apple.com
Thu Sep 8 09:16:05 PDT 2011


The Lion libdispatch source already uses clang's __sync_swap() for dispatch_atomic_xchg() when available, c.f. src/shims/atomic.h

#if __has_builtin(__sync_swap)
#define dispatch_atomic_xchg(p, n) \
		((typeof(*(p)))__sync_swap((p), (n)))
#else
#define dispatch_atomic_xchg(p, n) \
		((typeof(*(p)))__sync_lock_test_and_set((p), (n)))
#endif

unless GCC 4.5.1 has something similar, switching dispatch_atomic_xchg() to an inline asm volatile("xchg") on intel when builiding with that compiler is the cleanest workaround IMO

Daniel

On Sep 8, 2011, at 8:34 AM, Dave Zarzycki wrote:

> Joakim,
> 
> GCC 4.5.1 is probably more strictly implementing __sync_lock_test_and_set(), which doesn't promise to be a full barrier. Unfortunately and historically speaking, __sync_lock_test_and_set() was the only way to get at the "xchg" instruction under GCC (short of gross inline asm() code), and that is what dispatch_atomic_xchg() uses. This is why we added __sync_swap() to clang:
> 
> http://clang.llvm.org/docs/LanguageExtensions.html#__sync_swap
> 
> …which does promise to be a full barrier and we hope to use someday instead of __sync_lock_test_and_set(). You might want to look to see if GCC has added any similar intrinsic to get at the 'xchg' instruction.
> 
> davez
> 
> 
> 
> On Sep 8, 2011, at 3:58 AM, Joakim Johansson wrote:
> 
>> We just filed http://libdispatch.macosforge.org/trac/ticket/35 after sometimes encountering spinning worker threads when running under high load on multi-cpu machines.
>> 
>> Various versions of gcc will optimize and reorder the code differently, but with 4.5.1 we run into this problem.
>> 
>> Is this a fundamental problem with libdispatch itself that will rear it’s ugly head if/when the Mac OS X system compiler is changed in the future (to optimize more aggressively), or is it a bug in the gcc 4.5.1 optimizer?
>> 
>> The Lion source code seems more or less unchanged here, so even if we tested this with the current r197 code base, the behavior should be the same when integrating the latest source drop.
>> 
>> Thoughts?
>> 
>> Thanks,
>> 
>> Joakim
>> 
>> 
>> _______________________________________________
>> libdispatch-dev mailing list
>> libdispatch-dev at lists.macosforge.org
>> http://lists.macosforge.org/mailman/listinfo.cgi/libdispatch-dev
> 
> _______________________________________________
> libdispatch-dev mailing list
> libdispatch-dev at lists.macosforge.org
> http://lists.macosforge.org/mailman/listinfo.cgi/libdispatch-dev



More information about the libdispatch-dev mailing list