Soup
Soup

Reputation: 1719

Should I wrap dispatch_group_leave in an @synchronized block?

Given the following code, is the @synchronized call un-required?

I assume that dispatch_group_enter/leave is atomic but it's not listed as thread safe here https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/dispatch_group_leave.3.html and I'm suddenly worried I've been messing up all this time.

// Imagine this is on its own queue already (possibly main, possibly not)
dispatch_group_t group = dispatch_group_create();
for(x in array){
  dispatch_group_enter(group);
  [x doSomethingAsync:^{
    // imagine x is part of a library which sometimes runs blocks on
    // a different queue.
    // surely dispatch_group_leave has its own internal synchronization?
    @synchronized(group){
      dispatch_group_leave(group);
    }
  }]
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

Upvotes: 1

Views: 597

Answers (2)

ipmcc
ipmcc

Reputation: 29886

You do not need to provide any additional synchronization when calling dispatch_group_enter and dispatch_group_leave. GCD is, itself, providing concurrency and threading tools. If additional synchronization or barriers were required, my expectation would be that it would be called out explicitly in the docs, much like the requirement for dispatch_once_ts to have global/static storage is called out. Put differently, GCD is a threading library, so the expectation is that, unless otherwise stated, it's calls are expected to provide thread safety relative to each other.

This expectation is based on much personal experience and on Greg Parker making a similar statement on a mailing list a while back.

Upvotes: 2

user623396
user623396

Reputation: 1547

Since you're not spawning threads you should not worry.

In your example dispatch_group_leave(group) is called on the same thread.

Upvotes: 0

Related Questions