@synchronized - Mutex identification?

Discussion in 'iOS Development' started by lauNchD, Dec 30, 2009.

  1. lauNchD

    lauNchD Well-Known Member

    Joined:
    Jan 27, 2008
    Messages:
    1,844
    Likes Received:
    261
    Device:
    iPhone 5 (Black)
    Hi!
    I have a small question regarding the @synchronized directive. (In a nutshell, it ensures that a piece of code isn't executed at the same time by two different threads, to protect data from being corrupted somehow.)

    Example:
    [OBJC]
    static NSMutableArray *classWideArray;

    + (void) initialize
    {
    if ([self class] == [MyClass class])
    classWideArray = [[NSMutableArray alloc] init];
    }

    - (void) myMultithreadedDataManipulationMethod

    Please Register or Log in to view images

    NSString*)anArgument
    {
    @synchronized(self)
    {
    // mutex: self
    // code that will be executed once at a time for self
    // [myArray addObject: anArgument];
    }
    @synchronized([self class])
    {
    // mutex: MyClass
    // code that will be executed once at a time for all instances of this class
    // [classWideArray addObject: anArgument];
    }
    } [/OBJC]

    However, I am not sure how @synchronized checks if two mutexes are the same. Does is use pointer equality (==) or -isEqual: ? I'm sort of confused because Apple does not seem to elaborate on that. I'm grateful for any pointers (pun fail) on this.
  2. Axis

    Axis Super Moderator Staff Member

    Joined:
    Dec 2, 2007
    Messages:
    6,288
    Likes Received:
    133
    Device:
    iPhone 4S (White)
    I don't know of the implementation any more than you do, but pointer comparison seems the most logical, as the issue is the same object being accessed simultaneously on different threads, not two or more equal objects.
  3. lauNchD

    lauNchD Well-Known Member

    Joined:
    Jan 27, 2008
    Messages:
    1,844
    Likes Received:
    261
    Device:
    iPhone 5 (Black)
    I know pointer comparison would be the most logical, but I saw this somewhere:
    [OBJC]
    -(void) myMethod
    {
    @synchronized(NSStringFromSelector(_cmd))
    {
    // Mutex: @"myMethod" (but dynamically created; probably not the same object every time)
    // Apparently, this method will only able to be executed once at a time, no matter what class or instance
    }
    }[/OBJC]
    Theoretically, the Obj-C runtime wouldn't be allowed to use -isEqual: because there is no guarantee that all classes implement this method/conform to NSObject.

    (@synchronized(@"blah") {} would most definitely work, though, because the string is a constant and always stays the same)

Share This Page