0
votes

I have a property (atomic, retain) NSString *identifier which may be read from multiple thread. So which is the correct way to make it thread safe-

- (NSString *)identifier
   {   @synchronized(self)   
      {
          return [_identifier retain] autorelease];   
      }

   }

or

  - (NSString *)identifier
       {    @synchronized(identifier)   
          { 
              return [_identifier retain] autorelease];   
          }

       }

Infact, i want to know the purpose of key parameter is @synchronize(key). Thanks for you help.

1
What exactly do you mean by "thread safe" in this context? Just that it won't crash when accessed, or that it has some special thread related functionality? - Joachim Isaksson
The auto-generated getter, with the (default) atomic attribute will do the right thing; why are you generating the getter yourself? - Droppy
@JoachimIsaksson, by thread-safe i mean data integrity.@Droppy atomic doesn't guarantee thread safety. - russell
Nor does your code. It does exactly the same thing as atomic, just slower. And why aren't you using ARC? - gnasher729
@gnasher729, how do you know atomic has same implementation? Apple made the implementation of atomic hidden, so there is no way to say that Apple use @synchronize() in their atomic implementation? And Apple clearly states that atomic doesn't provide thread safety, it only guarantee whole/viable value. - russell

1 Answers

0
votes

The argument for @synchronized is the object on which synchronisation happens. Every other @synchronized(self) with the same object will stop while another @synchronized(self) is executing.

You might want to post code that actually compiles. That would tell you that the second one doesn't actually compile.