The semantics for using a dispatch semaphore are as follows:
-
When you create the semaphore (using the dispatch_semaphore_create function), you can specifya positive integer indicating the number of resources available.
-
In each task, call dispatch_semaphore_wait to wait on the semaphore.
-
When the wait call returns, acquire the resource and do your work.
-
When you are done with the resource, release it and signal the semaphore by calling the dispatch_semaphore_signal function.
// Create the semaphore, specifying the initial pool size dispatch_semaphore_t fd_sema = dispatch_semaphore_create(getdtablesize() / 2); // Wait for a free file descriptor dispatch_semaphore_wait(fd_sema, DISPATCH_TIME_FOREVER); fd = open("/etc/services", O_RDONLY); // Release the file descriptor when done close(fd); dispatch_semaphore_signal(fd_sema);
When you create the semaphore, you specify the number of available resources. This value becomes the initialcount variable for the semaphore. Each time you wait on the semaphore, the dispatch_semaphore_waitfunction decrements that count variable by 1. If the resulting value is negative, the function tells the kernel toblock your thread. On the other end, the dispatch_semaphore_signal function increments the countvariable by 1 to indicate that a resource has been freed up. If there are tasks blocked and waiting for a resource,one of them is subsequently unblocked and allowed to do its work.