• 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
    ",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
    ",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);
        
      }
    }
    

      

     
     
  • 相关阅读:
    AngularJS
    Java
    Java
    AngularJS
    Java
    Java
    AngularJS
    Java
    Debian
    Java
  • 原文地址:https://www.cnblogs.com/lean-blog/p/13713716.html
Copyright © 2020-2023  润新知