Twilite Twilite - 1 month ago 12
Objective-C Question

Using @synchronized, volatile and OSMemoryBarrier() all together. Does one imply the other?

Coming from Java I'm trying to learn thread safety in Objective-C. So far I've leaned that


  • @synchronized blocks prevent concurrent access to the same block of code

  • volatile variables assure visibility of changes accross threads

  • OSMemoryBarrier(); assures proper ordering of access



My question is: Does one of those imply one or more of the others? If I want all three, do I need to use all three techniques?

Example:

volatile int first = 0;
volatile int second = 0;

[...]

@synchronized {
OSMemoryBarrier();
first++;
OSMemoryBarrier();
second++;
OSMemoryBarrier();
}


In Java all three are assured when entering and leaving a synchronized block and when reading or writing a volatile variable. True?

Answer

The @synchronized directive gets converted as follows...

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

becomes...

- (NSString *)myString {
  NSString *retval = nil;
  pthread_mutex_t *self_mutex = LOOK_UP_MUTEX(self);
  pthread_mutex_lock(self_mutex);
  retval = [[myString retain] autorelease];
  pthread_mutex_unlock(self_mutex);
  return retval;
}