2012-01-10 80 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() 
相關問題