【发布时间】:2012-02-06 20:17:28
【问题描述】:
是否可以在 ios 应用程序中实现计数信号量?
【问题讨论】:
标签: objective-c ios semaphore
是否可以在 ios 应用程序中实现计数信号量?
【问题讨论】:
标签: objective-c ios semaphore
是的,这是可能的。 有很多可用的同步工具:
我建议阅读“Threading Programming Guide”并询问更具体的内容。
【讨论】:
像这样:
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[self methodWithABlock:^(id result){
//put code here
dispatch_semaphore_signal(sem);
[self methodWithABlock:^(id result){
//put code here
dispatch_semaphore_signal(sem);
}];
}];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
信用http://www.g8production.com/post/76942348764/wait-for-blocks-execution-using-a-dispatch
【讨论】:
我无法找到一个本地 IOS 对象来执行此操作,但使用 C 库可以正常工作:
#import "dispatch/semaphore.h"
...
dispatch_semaphore_t activity;
...
activity = dispatch_semaphore_create(0);
...
dispatch_semaphore_signal(activity);
...
dispatch_semaphore_wait(activity, DISPATCH_TIME_FOREVER);
希望对您有所帮助。
【讨论】:
在 Swift 3 中,您可以使用 @987654321@。
// initialization
let semaphore = DispatchSemaphore(value: initialValue)
// wait, decrement the semaphore count (if possible) or wait until count>0
semaphore.wait()
// release, increment the semaphore count
semaphore.signal()
【讨论】: