zoukankan      html  css  js  c++  java
  • Linux 线程的互斥和等待 pthread_mutex_lock/pthread_mutex_unlock pthread_cond_wait/pthread_cond_signal

    多线程中比较常见的是生产者,消费者的模式。而实现它并不复杂,通过 pthread_mutex_lock/pthread_mutex_unlock pthread_cond_wait/pthread_cond_signal 就可以达到目的:

    非常容易犯的错误是,忘记对 mutex 和 mwait 的初始化,有时候会出现非常难以发现的问题。

    #include <pthread.h>

    pthread_mutex_t mutex;
    pthread_cond_t mwait;

    bool exit_sign;

    void init() {

     pthread_mutex_init(mutex, NULL);
     pthread_cond_init(mwait, NULL);

    }

    void relese() {

    exit_sign = 1;

    pthread_mutex_unlock(mutex);

    pthread_cond_signal(mwait);

    pthread_mutex_destroy(mutex);
    pthread_cond_destroy(mwait);

    }

    void
    pushD(D *data) { pthread_mutex_lock(&D_mutex); if (D_queue.size() >= maxQueueSize) { delete (D_queue.front()); D_queue.pop();
       }
    D_queue.push(data); pthread_mutex_unlock(&mutex); pthread_cond_signal(&mwait); return 0; } D* popD() { pthread_mutex_lock(&mutex); D *d = NULL; while (D_queue.size() <= 0 && !exit_sign) { pthread_cond_wait(&mwait, &mutex); } if (exit_sign) { return NULL; } d = D_queue.front(); D_queue.pop(); pthread_mutex_unlock(&mutex); return d; }

     

  • 相关阅读:
    flex 居中并两端对齐
    搭建Docker环境---私有仓库registry搭建
    搭建Docker环境---常用命令
    搭建Docker环境---Docker安装(centos7)
    搭建Docker环境---Docker概述
    Shell脚本
    安装webstrom2019
    mysql主从配置
    MySql5.7安装(centos 7)
    MySQL父子节点查询
  • 原文地址:https://www.cnblogs.com/beautiful-scenery/p/3589601.html
Copyright © 2011-2022 走看看