如果互斥锁被占用,另一个线程进入时,互斥锁会引起线程切换。
适合锁的内容比较多的
自旋锁,如果锁被占用,来了的线程会一直等待直到获取这把锁相当于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* run(void*arg)
{
int *p=(int*)arg;
while((*p) < 100000)
{
pthread_spin_lock(&spinlock);
(*p)++;
pthread_spin_unlock(&spinlock);
printf("pthread_self %lu, count = %d\n", pthread_self(),*p);
usleep(1);
}
pthread_exit(NULL);
}
int main(int argc,char*argv[]){
if (argc!=2)
{
printf("+num\n");
return 1;
}
pthread_t tid[10]={0};
pthread_spin_init(&spinlock,PTHREAD_PROCESS_SHARED);
int i,j;
int count=0;
int num=atoi(argv[1]);
for ( i = 0; i < num; ++i)
{
pthread_create(&tid[i],NULL,run,(void*)&count);
}
for ( j = 0; j < num; ++j)
{
pthread_join(tid[j],NULL);
}
pthread_spin_destroy(&spinlock);
return 0;
}