zoukankan      html  css  js  c++  java
  • 对pthread_cond_wait()函数的理解

     对pthread_cond_wait()函数的理解(我在CU上回复一个人的问题的解答) (个人见解,如有错误,恳请大家指出) /************pthread_cond_wait()的使用方法**********/     pthread_mutex_lock(&qlock);        pthread_cond_wait(&qready, &qlock);     pthread_mutex_unlock(&qlock); /*****************************************************/ The mutex passed to pthread_cond_wait protects the condition.The caller passes it locked to the function, which then atomically places the calling thread on the list of threads waiting for the condition and unlocks the mutex. This closes the window between the time that the condition is checked and the time that the thread goes to sleep waiting for the condition to change, so that the thread doesn't miss a change in the condition. When pthread_cond_wait returns, the mutex is again locked. 上面是APUE的原话,就是说pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)函数传入的参数mutex用于保护条件,因为我们在调用pthread_cond_wait时,如果条件不成立我们就进入阻塞,但是进入阻 塞这个期间,如果条件变量改变了的话,那我们就漏掉了这个条件。因为这个线程还没有放到等待队列上,所以调用pthread_cond_wait前要先锁 互斥量,即调用pthread_mutex_lock(),pthread_cond_wait在把线程放进阻塞队列后,自动对mutex进行解锁,使得 其它线程可以获得加锁的权利。这样其它线程才能对临界资源进行访问并在适当的时候唤醒这个阻塞的进程。当pthread_cond_wait返回的时候又自动给mutex加锁。 实际上边代码的加解锁过程如下: /************pthread_cond_wait()的使用方法**********/ pthread_mutex_lock(&qlock);    /*lock*/ pthread_cond_wait(&qready, &qlock); /*block-->unlock-->wait() return-->lock*/ pthread_mutex_unlock(&qlock); /*unlock*/ /*****************************************************/

  • 相关阅读:
    [编程题] 微信红包
    MYSQL实现主从复制
    有关windows系统的EXE和DLL文件说法错误
    Http错误代码
    一步步优化JVM四:决定Java堆的大小以及内存占用
    一步步优化JVM三:GC优化基础
    一步步优化JVM二:JVM部署模型和JVM Runtime
    一步步优化JVM一:概述、方法及需求
    排查Java线上服务故障的方法和实例分析
    【转】Zookeeper-Watcher机制与异步调用原理
  • 原文地址:https://www.cnblogs.com/hdjsjlbs/p/3324332.html
Copyright © 2011-2022 走看看