0

I have a -(void) downloadFile method that can be called from multiple threads. I'd like to create a situation where ONLY a single thread can execute the method - the first thread that's ready; Other threads should SKIP the call and just continue with their other job (without blocking\waiting for anything).

What mechanism should I use to achieve that?

4

1 回答 1

0

Here is a simple way to achieve that.

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];

Make sure you are using the same object for @synchronize. self might be different objects for different threads depending on your implementation. If that is not convenient just use NSLock.

于 2013-07-14T23:48:06.263 回答