如何在iOS应用程序中实现信号量?

是否有可能在ios应用程序中实现计数信号量?

对的,这是可能的。 有相当多的同步工具可用:

  • @Synchronized
  • NSLock
  • NSCondition
  • NSConditionLock
  • GCD信号量
  • pthread锁

我build议阅读“ 线程编程指南 ”,并提出更具体的问题。

喜欢这个:

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

我无法find一个本地的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中,你可以使用DispatchSemaphore

 // 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()