用途:
使用Dispatch Semaphore控制有限资源的访问
说明:
如果提交到 dispatch queue 中得任务需要访问某些有限资源,可以使用dispatch semaphore 来控制同时访问这个资源的任务数量。 dispatch semaphore 和普通的信号量类似,唯一的区别是当资源可用时,需要更少的时间来获得dispatch semaphore。
使用过程:
1. 使用 dispatch_semaphore_create 函数创建semaphore, 指定正数值表示资源的可用数量。
2. 在每个任务中,调用dispatch_semaphore_wait 来等待 Semaphore
3. 在上面调用返回时,获得资源并开始工作
4. 使用完资源后,调用 dispatch_semaphore_signal 函数释放和 signal这个 semaphore
实例:
// 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);