Re: How to count Atoms
Re: How to count Atoms
- Subject: Re: How to count Atoms
- From: Quincey Morris <email@hidden>
- Date: Fri, 07 Oct 2016 10:05:47 -0700
- Feedback-id: 167118m:167118agrif8a:167118s1y6_KlIuo:SMTPCORP
On Oct 7, 2016, at 09:24 , Jens Alfke <email@hidden> wrote:
>
> IMO dispatch_semaphore is overkill for this; it’s not just an atomic counter, it’s also got blocking behaviors for use in e.g. managing a pool of resources.
I wasn’t suggesting using dispatch_semaphore itself as the atomic counter, but rather as an atomicity strategy for a separate increment calculation. So, yes, it’s overkill compared to a true atomic increment operation, but (being pretty much just an increment/decrement each time it’s hit) it’s pretty cheap as overhead goes (unlike @synchronized).
> I’ll bet that most Mac/iOS programmers don’t know about it, let alone people coming from other platforms.
>
> The simplest solution is just to use an atomic operation. Even if there isn’t a standard atomic API in C (as there is in C++), anyone reading the code is probably going to understand what OSAtomicIncrement32() does just from its name.
Surely “anyone reading the code” is going to recognize “dispatch_semaphore” as something to do with a semaphore, including people from other platforms? Of course, there may still be a lot of programmers from all platforms who don’t know what a semaphore is, period.
Anyway, part of my reason for suggesting dispatch_semaphore is that it’s an easy, useful tool to know, to make any kind of operation atomic, not just incrementing — as well as its more general purpose of managing a pool of resources.
It’s also worth noting that *no* direct mechanism for atomic incrementing (currently) exists in Swift. There is no language syntax that specifies an atomic property, and existing APIs such as OSAtomicIncrement32 do *not* work when called from Swift code, because they do not conform to the Swift memory model. Presumably this will be remedied at some future time, but until then it’s necessary to use alternative strategies such as semaphores.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden