Should I synchronize with self or with the method argument?
Asked Answered
M

1

2

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]) {
        //...
Meaty answered 17/3, 2014 at 18:5 Comment(1)
multiple threads are accessing self?Anguish
I
7

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).

Influx answered 17/3, 2014 at 18:26 Comment(2)
On the (thing) version does this also block code on different method with the same object? destroy(thing) alter(thing)Meaty
Thanks very much. All the documentation I have been reading yet the answer was never written better than you have done it here.Meaty

© 2022 - 2024 — McMap. All rights reserved.