They both use a counter and use a lock to protect the increment and decrement of the counter, and when the counter is less than zero, the thread waits. It seems to me that they are the same except for their api.
3 Answers
Apple writes in their documentation regarding DispatchSemaphore
signal()
method:
this function wakes a thread currently waiting in dispatch_semaphore_wait(::).
Unlike DispatchSemaphore
, NSCondition
has 2 different methods:
1) broadcast()
:
Signals the condition, waking up all threads waiting on it.
2) signal()
Signals the condition, waking up one thread waiting on it.
I think a dispatch semaphore is a higher level concept which doesn't necessarily involve locking if not needed, while NSCondition is a wrapper around pthread's conditions, thus always involving locking at the thread level.
Dispatch semaphores work in tandem with dispatch queues and not every dispatch queue is necessarily on a different thread (because of the usage of thread pools).
An NSCondition would have to be used in the classic way which involves the following steps:
On the waiting side:
- lock the condition
- in a while loop, check the predicate and wait for the condition
- unlock the condition
On the signalling/broadcasting side:
- lock the condition
- change the underlying values which would change the predicate
- signal/broadcast the condition
- unlock the condition
Example category which demonstrates the usage of NSCondition (Objective C):
@implementation NSCondition(Extension)
- (void)signalPredicateModification:(void (NS_NOESCAPE ^)(void))predicateModification {
@try {
[self lock];
predicateModification();
[self signal];
} @finally {
[self unlock];
}
}
- (void)waitForPredicate:(BOOL (NS_NOESCAPE ^)(void))predicate {
@try {
BOOL predicateResult = NO;
[self lock];
while (!(predicateResult = predicate())) {
[self wait];
}
} @finally {
[self unlock];
}
}
@end
A dispatch semaphore's usage is much simpler in that you don't require to lock it and you can use it as a predicate directly. It simply acts as a counter where each wait decreases its value and each signal increases it. Its use might be limited for more complex predicates for which an additional lock would be required.
From the documentation:
A dispatch semaphore is an efficient implementation of a traditional counting semaphore. Dispatch semaphores call down to the kernel only when the calling thread needs to be blocked. If the calling semaphore does not need to block, no kernel call is made.
With DispatchSemaphore
you must take care to balance each wait()
with a signal()
. NSCondition
, aside from allowing more flexible types of predicates, is more flexible about waiting. If the predicate is already true, an unlimited number of readers can be satisfied. And if it’s not yet true, a single broadcast()
can wake up multiple waiters.