跟mutex的区别是mutex是拿不到锁就睡眠,spinlock是拿不到锁就自旋。

自旋锁

自旋锁的概念有两种,一种是OS级别的自旋锁,也就是spinlock,另一种是语言平台实现的自旋,比如ReentrantLock。

ReentrantLock的自旋

image.png

Linux OS的自旋

pthread_spinlock_init 定义

image.png :::tips int pthread_spin_destroy(pthread_spinlock_t lock);
int pthread_spin_init(pthread_spinlock_t
lock, int pshared); :::

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. int sharei = 0;
  5. void increase_num(void);
  6. //定义一把自旋锁
  7. pthread_spinlock_t a_lock;
  8. int main()
  9. {
  10. //初始化自旋锁
  11. pthread_spin_init(&a_lock, 0);
  12. int ret;
  13. pthread_t thread1,thread2,thread3;
  14. ret = pthread_create(&thread1,NULL,(void *)&increase_num,NULL);
  15. ret = pthread_create(&thread2,NULL,(void *)&increase_num,NULL);
  16. ret = pthread_create(&thread3,NULL,(void *)&increase_num,NULL);
  17. pthread_join(thread1,NULL);
  18. pthread_join(thread2,NULL);
  19. pthread_join(thread3,NULL);
  20. printf("sharei = %d\n",sharei);
  21. return 0;
  22. }
  23. void increase_num(void)
  24. {
  25. long i,tmp;
  26. for(i =0;i<=9999;++i)
  27. {
  28. // lock spin 自旋
  29. pthread_spin_lock(&a_lock);
  30. tmp=sharei;
  31. tmp=tmp+1;
  32. sharei = tmp;
  33. pthread_spin_unlock(&a_lock);
  34. }
  35. }