zoukankan      html  css  js  c++  java
  • 关于条件变量

    最近打算在写一个网络库,涉及到对mutex、condition的封装,再次使用Linux提供的接口,发现一个问题,使用condition的时候需要配合一个mutex来使用。

    上面是关于pthread_cond_wait的man手册说明,意思就是再调用pthread_cond_wait之前需要把mutex上锁,pthread_cond_wait会自动解锁,然后等待条件变量被signal,执行线程会被挂起并不会消耗任何CPU时间,知道条件变量被signal。在返回到调用线程之前,pthread_cond_wait会重新获取锁(如果获取不到锁,会阻塞)。

    我想要测试就是最后一点,如果在返回的时候获取不到锁,会不会阻塞,以及想知道为什么需要与一个mutex配合使用。

    测试代码:

     1 /*
     2 * 测试pthread_cond_wait
     3 */
     4 #include <unistd.h>
     5 #include <pthread.h>
     6 
     7 #include <stdio.h>
     8 
     9 pthread_mutex_t mutex;
    10 pthread_cond_t cond;
    11 
    12 void* mutex_func(void *arg)
    13 {
    14     // wait cond_func get the lock
    15     printf("lock after 5s
    ");
    16     sleep(5);
    17     pthread_mutex_lock(&mutex);
    18 
    19     pthread_cond_signal(&cond);
    20 
    21     printf("unlock after 5s
    ");
    22     sleep(5);
    23     pthread_mutex_unlock(&mutex);
    24 }
    25 
    26 void* cond_func(void *arg)
    27 {
    28     // lock
    29     pthread_mutex_lock(&mutex);
    30 
    31     pthread_cond_wait(&cond, &mutex); // unlock and block
    32     printf("get signal
    ");
    33 
    34     pthread_mutex_unlock(&mutex);
    35     // acquire lock, will block
    36     printf("cond_func
    ");
    37 }
    38 
    39 int main(void)
    40 {
    41     pthread_mutex_init(&mutex, NULL);
    42     pthread_cond_init(&cond, NULL);
    43 
    44     pthread_t pid1, pid2;
    45     pthread_create(&pid1, NULL, mutex_func, NULL);
    46     pthread_create(&pid2, NULL, cond_func, NULL);
    47 
    48     pthread_join(pid1, NULL);
    49     pthread_join(pid2, NULL);
    50 
    51     return 0;
    52 }

    输出结果:

    结论:

    根据输出结果可以知道,确实是它需要的mutex释放之后才从pthread_cond_wait返回的。此处可以推测(需要看源码验证)pthread_cond_wait是去查看某一个条件是否为真来决定是否返回的(那么就涉及到了race condition),所以需要使用mutex来保护。

    源码验证:

  • 相关阅读:
    WPF、UWP以及其他类型项目的csproj文件的迁移(SDK-Style)
    文书生成笔录预设保存按钮Mq中间转传服务
    卷宗添加争议焦点数据制造脚本(卷宗部分)
    案件信息同步之后,文书系统案件名称显示不正确问题
    DISTINCT----mysql移除返回的重复值
    Nginx系列教程(6)Nginx location 匹配规则详细解说
    转载 chrony 详解
    dmesg 时间转换
    axios---get和post用法详解
    通过递归来封装sessionStorage---set/get/delete
  • 原文地址:https://www.cnblogs.com/lit10050528/p/7580422.html
Copyright © 2011-2022 走看看