Вопрос

In a method like this, which do synchronize (i.e. self or thing)?

- (BOOL)deleteThing:(MSThing *)thing error:(NSError **)error
{
    @synchronized(self)  {
        if (!thing) {
            return YES;
        }

        NSString *fileName = [[self thingDirectory] stringByAppendingPathComponent:thing.cacheInstanceName];

        if (![[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
        //...

=== OR ===

- (BOOL)deleteThing:(MSThing *)thing error:(NSError **)error
{
    @synchronized(thing)  {
        if (!thing) {
            return YES;
        }

        NSString *fileName = [[self thingDirectory] stringByAppendingPathComponent:thing.cacheInstanceName];

        if (![[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
        //...
Это было полезно?

Решение

In the first case,

@synchronized(self)  { ... }

the code will not be executed simultaneously by two threads calling the method on the same instance (self). This is probably what you want if the code accesses or modifies the instance in a thread-unsafe way.

In the second case,

@synchronized(thing)  { ... }

the code will not be executed simultaneously by two threads calling the method with the same argument (thing).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top