zoukankan      html  css  js  c++  java
  • pthread_cond_wait避免线程空转

    多线程对同一块区域进行操作时,需要定义如下两种类型的变量:

    pthread_mutex_t xxx;
    pthread_cond_t yyy;

    pthread_mutex_t类型的变量,即锁,对公共区域的操作进行同步;

    pthread_cond_t类型的变量,用来对事件状态进行检测。

    举例:读线程从队列中读取数据,当队列为空时,调用pthread_cond_wait函数阻塞自己,直到队列中有数据;写线程向队列中写入数据,如果队列之前的状态为空,写线程调用pthread_cond_signal函数唤醒正在被阻塞的读线程。

    线程调用pthread_cond_wait阻塞自己可以让出cpu资源,避免线程在while(1)循环中空转,耗尽cpu资源。

    常用函数:

    int pthread_mutex_init(pthread_mutex_t *restrict mutex,
                  const pthread_mutexattr_t *restrict attr);
    int pthread_mutex_destroy(pthread_mutex_t *mutex);
    int pthread_mutex_lock(pthread_mutex_t *mutex);
    int pthread_mutex_unlock(pthread_mutex_t *mutex);
    
    int pthread_cond_init(pthread_cond_t *restrict cond,
                  const pthread_condattr_t *restrict attr);
    int pthread_cond_destroy(pthread_cond_t *cond);
    int pthread_cond_signal(pthread_cond_t *cond);
    int pthread_cond_wait(pthread_cond_t *restrict cond,
                  pthread_mutex_t *restrict mutex);
  • 相关阅读:
    VS快捷键
    eclipse快捷键(shift+ctrl+l能出来所有的快捷键)
    永远不要觉得自己代码有多6
    winform中使用webBrowser时如何与JS交互
    HTML CSS
    HTTP 协议 session cookie
    [Python3]Python官方文档-Python Manuals
    [python3]PyCharm编辑器
    Loadrunner上传文件与下载文件脚本
    Spotlight安装
  • 原文地址:https://www.cnblogs.com/tanghuimin0713/p/4029541.html
Copyright © 2011-2022 走看看