For the More Curious: Read/Write Locks

Both Cocoa and pthreads provide read/write locks. These allow a data structure to be read by a number of readers simultaneously but only allow one thread write access at a time.

pthread_rwlock_t works just like pthread_mutex_t but with a couple of extra calls. Here are the details:

pthread_rwlock_init (pthread_rwlock_t *lock,
                     const pthread_rwlockattr_t *attr);

OS X does not define PTHREAD_RWLOCK_INITIALIZER, so you cannot create them statically.

int pthread_rwlock_destroy (pthread_rwlock_t *lock);

Rather than use lock(), you specify which kind of locking you want:

  • int pthread_rwlock_rdlock (pthread_rwlock_t *rwlock);
  • int pthread_rwlock_tryrdlock (pthread_rwlock_t *rwlock);
  • int pthread_rwlock_wrlock (pthread_rwlock_t ...

Get Advanced Mac OS X Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.