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
  • 相关阅读:
    Qt数据库操作
    Ubuntu12.04下Qt连接MySQL数据库
    VS2010下MFC的串口编程
    Ubuntu12.04(64bit)下安装Qt4总结
    Ubuntu12.04软件安装指南
    VirtualBox中安装Fedora9及其ARM开发环境配置
    Qt5+VS2010的安装及使用
    【MATLAB】边缘提取效果
    【Photoshop】批处理与快捷批处理
    【C#】WinForm 之 SQL Server 服务监控器(避免开机启动服务)
  • 原文地址:https://www.cnblogs.com/Anonytt/p/15570718.html
Copyright © 2011-2022 走看看