linux 自旋锁的简单理解

参考:https://blog.csdn.net/daiyudong2020/article/details/52202526

自旋锁和互斥锁,是有点相似的锁机制,

资源方面,自旋锁占用的资源比较少,互斥锁占用的资源比较多,

执行速率方面,如果阻塞的时间较短,则使用自旋锁比较好,否则,使用互斥锁,

阻塞方面,如果线程a想要加锁的锁被占用,自旋锁则不停地等待询问锁是否被释放,互斥锁则加入等待队列,等待锁被释放。

/***************************************************
##filename      : spin.c
##author        : GYZ                               
##e-mail        : [email protected]                 
##create time   : 2018-10-12 10:22:02
##last modified : 2018-10-12 10:51:33
##description   : NA                                
***************************************************/
#include                                   
#include                                  
#include                                  
#include 
#include 
                                                    
pthread_spinlock_t spin;
                        
void *spinlockFun1(void *arg)
{
	int num = 10;
	int i = 0;
	for(; i < 10000; ++i)
	{
		pthread_spin_lock(&spin);
		num ++;
		pthread_spin_unlock(&spin);		
	}
	printf("%s",__func__);
	printf("\n");
}
void *spinlockFun2(void *arg)
{
	int num = 10;
	int i = 0;
	for(; i < 10000; ++i)
	{
		pthread_spin_lock(&spin);
		num ++;
		pthread_spin_unlock(&spin);		
	}
	printf("%s",__func__);
	printf("\n");
}
                            
int main(int argc,char *argv[])                     
{                                                   
    pthread_t tid1;
	pthread_t tid2;
	int err1,err2;
	/*1,initialize spin lock*/
	pthread_spin_init(&spin,PTHREAD_PROCESS_PRIVATE);
	/*2.1,create thread 1*/
    err1 = pthread_create(&tid1,NULL,spinlockFun1,NULL);
	if(0  != err1)
	{
		printf("can't create thread1\n");
	}     
	/*2.2,create thread 2*/                              
    err2 = pthread_create(&tid2,NULL,spinlockFun2,NULL);
	if(0  != err2)
	{
		printf("can't create thread2\n");
	}      
	/*3.1,wait for the thread1 to end and recycle resources*/                             
	pthread_join(tid1,NULL);
	/*3.2,wait for the thread2 to end and recycle resources*/
	pthread_join(tid2,NULL);
	/*4,destory the spin lock*/
	pthread_spin_destroy(&spin);         
	return 0;                                   
}                                                   
                                                    
                                                    

关于,初始化锁,加锁,是否锁等的函数讲解,可参考:

https://www.cnblogs.com/chris-cp/p/5413445.html

你可能感兴趣的:(C和C++编程学习)