> On 8 Oct 2016, at 05:01, Quincey Morris <quinceymor...@rivergatesoftware.com> 
> wrote:
> 
> On Oct 7, 2016, at 07:49 , Gerriet M. Denkmann <g...@mdenkmann.de> wrote:
>> 
>> Is there a better way than this:
>> dsema = dispatch_semaphore_create( 0 );               
>> 
>> some loop to be counted
>> {
>>      dispatch_semaphore_signal(dsema); 
>>      ….
>> }
>> 
>> NSUInteger counter = 0;
>> for(;;)
>> {
>>      long a = dispatch_semaphore_wait(dsema, DISPATCH_TIME_NOW);
>>      if ( a != 0 ) break;
>>      counter++;
>> };
> 
> Er, I didn’t pay enough attention to this when you posted. No, this isn’t the 
> correct approach. You’re supposed to be using the semaphore as a lock. In 
> theory, you’d do it like this:
> 
>>      dsema = dispatch_semaphore_create (1);
>> 
>>      NSUInteger counter = 0;
>> 
>>      for …
>>      {
>>              …
>>              dispatch_semaphore_wait (dsema, <forever>);
>>              counter++;
>>              dispatch_semaphore_signal (dsema);
>>      }
> 
> That is, the semaphore controls access to a pool of 1 resources (the resource 
> being permission to increment the counter), and you wait on the resource to 
> become available (“lock”), increment the counter, then release the resource 
> (“unlock”).

This looks much better. 
But, alas, it is also much slower: overhead almost 40 sec (whereas my 
admittedly rather hackish way took less then half a second).

B.t.w.: I also tried NSLock - it is even slower (but not much) than 
@synchronized.

My preferred way to count (not deprecated and fast, but, as you said, probably 
not available in Swift) is:

#import <stdatomic.h>                    
atomic_uint_fast64_t counter;
atomic_fetch_add_explicit( &counter, 1, memory_order_relaxed );

I have no idea, whether atomic_uint_fast64_t is correct (there also is 
atomic_uint_least64_t — what is the difference ?)
and what memory_order_relaxed means (Xcode suggested this to me while warning 
about deprecation of OSAtomicIncrement64).

I looked at <http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf> (as 
kindly mentioned by Alastair). 
In “7.17.6 Atomic integer types” it says: “The semantics of the operations on 
these types are defined in 7.17.7”. 
But 7.17.7 does not mention any difference between atomic_uint_fast64_t and 
atomic_uint_least64_t.


Kind regards,

Gerriet.


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to