2012-01-10 79 views

回答

14

是的,这是可能的。 有相当多的同步工具可供选择:

  • @synchronized
  • NSLock
  • NSCondition
  • NSConditionLock
  • GCD信号灯
  • 并行线程锁
  • ...

我建议您阅读“Threading Programming Guide”并提出更具体的问题。

+0

和OSSpinLock。 – Jano 2012-01-10 12:24:23

+0

@synchonized是我的最爱。如果没有明显的对象阻塞,则将其与全局对象(如静态NSNumber)一起使用。坚持一个信号量模型可能有助于提高可读性等。 – 2012-01-10 13:39:09

+0

在全局对象上同步是一个坏主意。你不知道是否有其他代码也可能同步它,所以你暴露自己有死锁的风险。始终在有限的可见性的情况下进行同步,这对于当前的任务来说是明确的。另外,不要在自我上同步;再次,你不知道还有什么可能使用同一个对象。 – occulus 2017-11-17 22:38:32

4

我无法找到一个本地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); 

希望有所帮助。

6

像这样:

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

3

斯威夫特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() 
相关问题