對比三種同步機制在高併發計數器場景下的性能:pthread_mutex、CPU 原子指令、基於原子操作自旋鎖。
pthread_mutex_lock(&mx);
++counter;
pthread_mutex_unlock(&mx);
InterlockedExchangeAdd (單指令、用戶態)InterlockedExchangeAdd(&counter, 1); // 原子 fetch-and-add
__sync_fetch_and_add__sync_fetch_and_add(&counter, 1);
// Windows
while (InterlockedExchange(&lock, 1)) Sleep(0);
++counter;
InterlockedExchange(&lock, 0);
// Linux
while (__sync_lock_test_and_set(&lock, 1)) usleep(2);
++counter;
__sync_lock_release(&lock);
| 平台 | pthread_mutex | 原子操作 | 原子自旋鎖 |
|---|---|---|---|
| Windows | ~2.8 秒 | ~0.3 秒 | ~0.2 秒 |
| Linux | ~2.5 秒 | ~0.25 秒 | ~0.18 秒 |
原子操作 > 原子自旋鎖 > 互斥鎖 (速度排名)。自旋鎖在低競爭、短臨界區時極快;高競爭下 CPU 空轉浪費,需 usleep/Sleep(0) 讓出時間片。
sc_atom.h#ifdef _MSC_VER
#define SC_ATOM_ADD(v,a) InterlockedExchangeAdd(&(v),(a))
#define SC_ATOM_LOCK(v) while(InterlockedExchange(&(v),1)) Sleep(0)
#define SC_ATOM_UNLOCK(v) InterlockedExchange(&(v),0)
#elif __GNUC__
#define SC_ATOM_ADD(v,a) __sync_fetch_and_add(&(v),(a))
#define SC_ATOM_LOCK(v) while(__sync_lock_test_and_set(&(v),1)) usleep(2)
#define SC_ATOM_UNLOCK(v) __sync_lock_release(&(v))
#endif
atomic_int C11 / GCC builtins / Win32 Interlocked)。pthread_mutex / CRITICAL_SECTION (Windows 輕量級互斥)。__sync_synchronize / MemoryBarrier)。usleep 參數需根據 CPU 核心數、負載調優 (典型 1~10μs)。