2013-07-14 41 views
0

我有一個-(void) downloadFile方法,可以從多個線程中調用。 我想創建一個情況,只有一個線程可以執行該方法 - 準備好的第一個線程;其他線程應該跳過這個調用並繼續其他工作(不要阻塞\等待任何事情)。代碼同步 - 阻止一個塊執行

我應該用什麼機制來實現這個目標?

回答

0

這是一個簡單的方法來實現。

BOOL _firstToAttempt;  // in a scope all threads can access 
... 

_firstToAttempt = YES; // before any of the threads start 

... 


// when a thread is ready to download 
BOOL shouldDownload = NO; 
@synchronize (self) 
{ 
    if (_firstToAttempt) 
    { 
     _firstToAttempt = NO; 
     shouldDownload = YES; 
    } 
} 
if (shouldDownload) [self downloadFile]; 

確保您使用的是@synchronize相同的對象。根據您的實施情況,self可能是不同線程的不同對象。如果這不方便,只需使用NSLock。