Using Dispatch Semaphores to Regulate the Use of Finite Resources

来源:互联网 发布:网络流行语大全 编辑:程序博客网 时间:2024/05/18 01:38

The semantics for using a dispatch semaphore are as follows:

  1. When you create the semaphore (using thedispatch_semaphore_createfunction), you can specifya positive integer indicating the number of resources available.

  2. In each task, calldispatch_semaphore_waitto wait on the semaphore.

  3. When the wait call returns, acquire the resource and do your work.

  4. When you are done with the resource, release it and signal the semaphore by calling the dispatch_semaphore_signalfunction. 


    // Create the semaphore, specifying the initial pool sizedispatch_semaphore_t fd_sema = dispatch_semaphore_create(getdtablesize() / 2);// Wait for a free file descriptordispatch_semaphore_wait(fd_sema, DISPATCH_TIME_FOREVER);fd = open("/etc/services", O_RDONLY);// Release the file descriptor when doneclose(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, thedispatch_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, thedispatch_semaphore_signalfunction 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. 


0 0
原创粉丝点击