C, C++

C] spinlock

slowcloud_ 2026. 3. 5. 00:04

https://man7.org/linux/man-pages/man3/pthread_spin_init.3.html

 

pthread_spin_init(3) - Linux manual page

 

man7.org

 

 

대기 시간이 짧을 경우, mutex보다 spinlock이 훨씬 빠르게 작업을 처리한다.

#include <pthread.h>
#include <stdio.h>

#define endl "\n"

#define THREAD_COUNT 1000

int value = 0;
pthread_spinlock_t spinlock;

void *f(void *data) {

  size_t idx = (size_t)data;

  for (int i = 0; i < 10; i++) {
    pthread_spin_lock(&spinlock);
    value++;
    // printf("i'm thread %zu, and value is %d now!" endl, idx, value);
    pthread_spin_unlock(&spinlock);
  }

  return 0;
}

int main() {
  pthread_t threads[THREAD_COUNT];

  if (pthread_spin_init(&spinlock, PTHREAD_PROCESS_PRIVATE)) {
    printf("failed to init spinlock!!");
    return 1;
  }

  for (int i = 0; i < THREAD_COUNT; i++)
    pthread_create(threads + i, NULL, f, (void *)(size_t)i);

  for (int i = 0; i < THREAD_COUNT; i++)
    pthread_join(*(threads + i), NULL);

  printf("now, the value is %d!" endl, value);

  return 0;
}

 

스핀락의 경우, 초기화 시 락을 프로세스 단위로 공유할 것인지에 대한 여부를 설정해주어야 한다.

프로세스 간 공유가 불필요하다면 PTHREAD_PROCESS_PRIVATE를 적용하면 된다.

 

출력 확인 및 스핀락의 성능을 확실히 활용하기 위해 쓰레드에서의 출력을 제거했다.

WSL2 arch linux 환경 기준 실행 결과이다. spinlock이 mutex보다 1.5배 빠르게 실행되는 것을 확인할 수 있다.