Hacker News new | ask | show | jobs
by richardwhiuk 4061 days ago
This is all claimed to do this for 'performance' but there's no figures in this document as to whether the incrementAndGet / decrementAndGet is any faster than @synchronize.

(I suspect it probably is, but fundamentally, @synchronize is implemented using compare and swap / other processor atomics, so it's probable that the difference is very slight - e.g. there's only a measurable difference if the thread is descheduled while holding a lock).

3 comments

The goal of the article isn't about sheer performance — there are plenty of notes about it. If it was about pure performance, it'd be recommending moving away from objc classes and methods and using C functions or C++ classes instead, like std::atomic<>.

It's meant to be a somewhat-easy-to-digest introduction to lock-free design, where applicable.

What @synchronized ends up doing is far more complex — it has to be, to ensure the correctness of its purposes: https://github.com/opensource-apple/objc4/blob/master/runtim...

@synchronized calls objc_sync_enter and objc_sync_exit. Source code is available[0]. Best case, the thread already has the object locked and only needs to increment a lock count. Worst case, it spin locks, searches through a linked list of existing locks, then needs to malloc a new entry and create a new mutex for it.

0: http://www.opensource.apple.com/source/objc4/objc4-646/runti...

It's actually more than you'd think -- @synchronized has to deal with re-entrant locks, try/catches that also release locks accordingly while bubbling exceptions, etc. There's a lot more to it than compare and swap.