如果互斥锁被占用,另一个线程进入时,互斥锁会引起线程切换。
适合锁的内容比较多的
自旋锁,如果锁被占用,来了的线程会一直等待直到获取这把锁相当于while(1);
适合锁的内容比较少的
当线程切换的代价远远比等待的代价大的时候,使用自旋锁
#include <pthread.h>
int pthread_spin_init(pthread_spinlock_t *lock int pshared);
int pthread_spin_destroy(pthread_spinlock_t *lock);
PTHREAD_PROCESS_PRIVATE
中的线程对自旋锁进行操作
与调用pthread_spin_init()的线程相同的进程。
(试图在进程之间共享自旋锁
导致未定义的行为。)
PTHREAD_PROCESS_SHARED
自旋锁可以由任何一根线中的任何一根来操作
可以访问包含锁的内存的进程
(即。,该锁可能位于共享内存对象中
在多个进程之间共享)。
#include<pthread.h>
#include<stdio.h>
#include<unistd.h>
#include <stdlib.h>
pthread_spinlock_t spinlock;
void