Linux操作系統的三種鎖機制


Java程序員也要知道一些底層知識

一、Linux操作系統的三種鎖機制:互斥鎖(metux)、自旋鎖(Spin)、信號量

 
二、互斥鎖-C語言使用-Java鎖會調用
 
 
 1)代碼編譯指令: gcc mutextest.c -o mutextest.out -pthread
2) C語言代碼:
  
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
//聲明全局變量sharei 和 方法
int sharei = 0;
void increase_num(void);
// add mutex --定義一個互斥鎖並初始化
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//主函數
int main()
{
  int ret;
  pthread_t thread1,thread2,thread3;
  ret = pthread_create(&thread1,NULL,(void *)&increase_num,NULL);
  ret = pthread_create(&thread2,NULL,(void *)&increase_num,NULL);
  ret = pthread_create(&thread3,NULL,(void *)&increase_num,NULL);
  // join 主線程等待子線程執行完成以后才結束
  pthread_join(thread1,NULL);
  pthread_join(thread2,NULL);
  pthread_join(thread3,NULL);
  printf("sharei = %d\n",sharei);
  return 0;
}
//run
void increase_num(void)
{
  long i,tmp;
  for(i =0;i<=9999;++i)
  {
     
    //上鎖
    pthread_mutex_lock(&mutex);
    
    //不加鎖 結果會小於30000 ,加鎖以后結果正確=3000
    tmp=sharei;
    tmp=tmp+1;
    
    sharei = tmp;
    //解鎖
    pthread_mutex_unlock(&mutex);
    
  }
}

  三、自旋鎖-C語言使用(Spin)

    

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int sharei = 0;
void increase_num(void);
//定義一把自旋鎖
pthread_spinlock_t a_lock;
int main()
{
    //初始化自旋鎖
  pthread_spin_init(&a_lock, 0);
  int ret;
  pthread_t thread1,thread2,thread3;
  ret = pthread_create(&thread1,NULL,(void *)&increase_num,NULL);
  ret = pthread_create(&thread2,NULL,(void *)&increase_num,NULL);
  ret = pthread_create(&thread3,NULL,(void *)&increase_num,NULL);
  pthread_join(thread1,NULL);
  pthread_join(thread2,NULL);
  pthread_join(thread3,NULL);
  printf("sharei = %d\n",sharei);
  return 0;
}
void increase_num(void)
{
  long i,tmp;
  for(i =0;i<=9999;++i)
  {
    // lock spin 自旋
    pthread_spin_lock(&a_lock);
    tmp=sharei;
    tmp=tmp+1;
    
    sharei = tmp;
    pthread_spin_unlock(&a_lock);
    
  }
}

  

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM