继多线程并发锁方案(互斥锁)之后。
自旋锁与互斥锁的比较:
代码的实现与mutex相似:
#include <stdio.h> #include <pthread.h> #define THREAD_COUNT 10 pthread_mutex_t mutex; pthread_spinlock_t spinlock; //spinlock定义 void *thread_callback(void *arg) { int *pcount = (int *)arg; int i = 0; while (i ++ < 100000) { #if 0 (*pcount) ++; // #elif 0 pthread_mutex_lock(&mutex); (*pcount) ++; // pthread_mutex_unlock(&mutex); #else pthread_spin_lock(&spinlock); (*pcount) ++; // pthread_spin_unlock(&spinlock); #endif usleep(1); } } int main () { pthread_t threadid[THREAD_COUNT] = {0}; pthread_mutex_init(&mutex, NULL); pthread_spin_init(&spinlock, PTHREAD_PROCESS_SHARED); //初始化,第二个参数是否进程共享 int i = 0; int count = 0; for (i = 0;i < THREAD_COUNT;i ++) { pthread_create(&threadid[i], NULL, thread_callback, &count); } for (i = 0;i < 100;i ++) { printf("count : %d\n", count); sleep(1); } }
代码结果: