Using Dispatch Semaphores to Regulate the Use of Finite Resources

The semantics for using a dispatch semaphore are as follows:

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

  2. In each task, call dispatch_semaphore_wait to 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_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. 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值