2013-07-14 72 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。