Mobile Development 19 min read

What Is a Lock? Understanding iOS Synchronization Primitives

This article explains the concept of locks in iOS, describing their purpose, the actions of acquiring and releasing, common lock types such as spin locks, mutexes, semaphores, and their implementations using OSSpinLock, pthread_mutex, NSCondition, NSLock, recursive locks, and read‑write locks, along with performance considerations and underlying principles.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
What Is a Lock? Understanding iOS Synchronization Primitives

What Is a Lock

A lock is a synchronization primitive used to prevent multiple threads from accessing the same resource simultaneously, thereby avoiding race conditions and program crashes.

Lock Operations

Locks have two fundamental operations: lock (acquire) and unlock (release) .

Common Lock Types

Spin Lock (Busy‑wait Lock)

Spin locks repeatedly attempt to acquire the lock in a tight loop until they succeed, which can waste CPU cycles if the lock is held for a long time.

while(抢锁(lock) == 没抢到) {
  
}

Because the thread continuously polls the lock state, the CPU performs useless work when the lock is unavailable.

Mutual‑Exclusion Lock (Mutex)

A mutex blocks the thread when the lock is not available, allowing the operating system to schedule other threads.

while(抢锁(lock) == 没抢到) {
  // 当前线程先去睡了,当这把锁的状态发生改变时再唤醒(lock);
}

Semaphore

Introduced by Dijkstra in 1965, a semaphore maintains a counter between 0 and a maximum value. Threads perform a wait operation that decrements the counter and a signal operation that increments it.

// 初始化同步对象
dispatch_semaphore_t lock = dispatch_semaphore_create(1);
// -1 操作
dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
// ... 你的业务代码
// +1 操作
dispatch_semaphore_signal(lock);

Why Locks Are Needed

Locks prevent resource contention when multiple threads read or modify the same data, ensuring program correctness.

How to Use Locks in iOS

The following iOS lock primitives are presented with their typical usage patterns and performance characteristics.

OSSpinLock (Deprecated)

OSSpinLock lock = OS_SPINLOCK_INIT;
for (int i = 0; i < count; i++) {
  OSSpinLockLock(&lock);
  // ...
  OSSpinLockUnlock(&lock);
}

OSSpinLock is a spin lock that has been deprecated after iOS 10 due to priority‑inversion problems.

pthread_mutex

pthread_mutex_t lock;
pthread_mutex_init(&lock, NULL);

pthread_mutex_lock(&lock);
// ...
pthread_mutex_unlock(&lock);

Provides a cross‑platform mutex; can be configured as normal, error‑checking, or recursive.

NSCondition

Wraps a POSIX condition variable and a mutex, enabling producer‑consumer patterns.

void consumer(void) {
  pthread_mutex_t mutex;
  pthread_mutex_init(&mutex, NULL);
  pthread_cond_t cond;
  // ...
  pthread_mutex_lock(&mutex);
  while (!data) {
    pthread_cond_wait(&cond, &mutex);
  }
  // process data
  pthread_mutex_unlock(&mutex);
}

void producer(void) {
  // similar setup
  pthread_mutex_lock(&mutex);
  // produce data
  pthread_cond_signal(&cond);
  pthread_mutex_unlock(&mutex);
}

NSLock

#define MLOCK \
- (void) lock { \
  int err = pthread_mutex_lock(&_mutex); \
  // error handling ... \
}

Encapsulates a pthread mutex with error‑checking attributes.

NSRecursiveLock

NSRecursiveLock *lock = [NSRecursiveLock new];
[lock lock];
// ...
[lock unlock];

Allows the same thread to acquire the lock multiple times.

@synchronized

NSObject *lock = [NSObject new];
@synchronized(lock) {
  // critical section
}

Objective‑C syntax sugar that automatically creates a recursive lock for the given object.

NSConditionLock

- (instance)initWithCondition:(NSInteger)conditionValue {
  self = [super init];
  if (!self) return nil;
  _condition = [NSCondition new];
  _condition_value = conditionValue;
  return self;
}

- (void)lockWhenCondition:(NSInteger)conditionValue {
  [_condition lock];
  while (conditionValue != _condition_value) {
    [_condition wait];
  }
}

- (void)unlockWhenCondition:(NSInteger)conditionValue {
  _condition_value = conditionValue;
  [_condition broadcast];
  [_condition unlock];
}

Combines a condition variable with a lock, useful for state‑based synchronization.

pthread_rwlock_t (Read‑Write Lock)

static pthread_rwlock_t rwLock;
pthread_rwlock_init(&rwLock, NULL);

// Reader
pthread_rwlock_rdlock(&rwLock);
// read data
pthread_rwlock_unlock(&rwLock);

// Writer
pthread_rwlock_wrlock(&rwLock);
// modify data
pthread_rwlock_unlock(&rwLock);

Allows multiple concurrent readers while writers obtain exclusive access. Proper attribute configuration (e.g., PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) avoids writer starvation.

Underlying Principles

Spin‑Lock Mechanics

A spin lock repeatedly checks a shared flag until it can set the flag atomically. On multi‑core CPUs, atomicity is achieved with hardware instructions such as LOCK on x86.

Atomic Operations

On a single processor, an operation is atomic if it cannot be pre‑empted. On multi‑processor systems, true atomicity requires hardware support.

Priority Inversion

When a low‑priority thread holds a lock and a high‑priority thread busy‑waits, the CPU time can be wasted, leading to priority inversion.

Performance Considerations

Spin locks have low lock/unlock latency but waste CPU if held for long periods.

Mutexes block the thread, causing a context switch, which is more expensive but avoids busy‑waiting.

Read‑write locks are efficient for read‑heavy workloads but can cause writer starvation without proper priority settings.

Practical Test Results

Benchmark data (in milliseconds) for 10 000 000 lock/unlock operations shows the relative performance of various iOS lock primitives.

References

pthread_mutex_lock – Open Group

Apple Thread Safety Guide

glibc pthread_mutex_lock implementation

Various pthread synchronization mechanisms

Conditional variable vs semaphore discussion on StackOverflow

pthread_rwlockattr_setkind_np manual page

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

performanceiOSconcurrencySynchronizationmultithreadingLocks
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.