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”).

In practice, you’d actually initialize the semaphore like this:

>       dsema = dispatch_semaphore_create (0); // start with a zero count
>       dispatch_semaphore_signal (dsema); // increment to the number of 
> resources in the pool.

That’s because if you create the semaphore with a non-zero count, then later 
try to release the semaphore object when its count is something different 
(which can happen if you have a more complex loop that you break out of), your 
app will crash. The API design assumption is that if you didn’t free all the 
original resources, your app has a bug (which I happen to think is bogus 
reasoning, but anyway…).


_______________________________________________

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