zoukankan      html  css  js  c++  java
  • 【系统编程】线程同步

     1 #include<stdio.h>
     2 #include<string.h>
     3 #include<pthread.h>
     4 #include<stdlib.h>
     5 #include<unistd.h>
     6 
     7 pthread_mutex_t mutex; //定义一把互斥锁 ,可以想象为 int mutex=1
     8 void *tfn(void *arg){
     9     srand(time(NULL));
    10     while(1){
    11         pthread_mutex_lock(&mutex); //加锁 ,想象为 mutex-- 
    12         printf("hello ");
    13         sleep(rand()%3);
    14         printf("world\n");
    15         pthread_mutex_unlock(&mutex); //解锁,想象为 mutex++
    16         sleep(rand()%3);
    17     }
    18     return NULL;
    19 }
    20 
    21 int main(void){
    22     pthread_t tid;
    23     srand(time(NULL));
    24 
    25     int ret = pthread_mutex_init(&mutex,NULL);  //初始化互斥锁
    26 
    27     pthread_create(&tid,NULL,tfn,NULL);
    28     while(1){
    29         pthread_mutex_lock(&mutex); //加锁
    30         printf("HELLO ");
    31         sleep(rand()%3);
    32         printf("WORLD\n");
    33         pthread_mutex_unlock(&mutex);//解锁
    34         sleep(rand()%3);
    35 
    36     }
    37     pthread_join(tid,NULL);
    38     return 0;
    39 }

     这里解释一下为什么Line15,33需要先解锁再sleep。不然的话其实就是不给另一个线程cpu调度的时间,直接执行while循环,会出现一直输出全部大写或者全部小写的情况,这不是我们期待的。我们期待的是大小写交替。

     

     读写锁:

      与互斥量类似,但读写锁允许更高的并行性,其特性为:写独占,读共享。

      锁只有一把。以读方式给数据加锁一一读锁,

            以写方式给数据加锁一一写锁

      读共享,写独占。

      写锁优先级高。

      相较于互斥量而言,当读线程多的时候,提高访问效率。

      

    条件变量:

     

    前ICPC算法竞赛退役选手|现摸鱼ing
  • 相关阅读:
    jvm基本结构和解析
    多态的意思
    java中对象的简单解读
    double类型和int类型的区别
    python 解析xml文件
    win10不能映射Ubuntu共享文件
    Qt程序打包
    Ubuntu boot分区文件误删,系统无法启动,怎么解
    ubuntu Boot空间不够问题“The volume boot has only 5.1MB disk space remaining”
    Ubuntu 分辨率更改 xrandr Failed to get size of gamma for output default
  • 原文地址:https://www.cnblogs.com/Anonytt/p/15570718.html
Copyright © 2011-2022 走看看