Dispatch Semaphore

用途:

使用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);






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值