zoukankan      html  css  js  c++  java
  • 一段使用 mutex 和 条件变量 pthread_cond_wait 的例子

    #include <iostream>
    #include 
    <pthread.h>
    #include 
    <string>
    #include 
    <unistd.h>

    using namespace std;

    int Number = 0;
    pthread_mutex_t NMutex;
    pthread_cond_t NCond;

    void *thread1(void *arg)
    {
            pthread_detach(pthread_self());
            pthread_mutex_lock(
    &NMutex);
            
    while (Number <= 0 )//等待主线程读入Number
                    pthread_cond_wait(&NCond, &NMutex);
            
    int Count = Number;
            
    int Sum = 1;
            
    for (int i = 1; i < Count; i++)
                    Sum 
    += i;
            cout 
    << "count by thread1 is " << Sum << endl;
            pthread_mutex_unlock(
    &NMutex);
            
    return NULL;
    }


    void *thread2(void *arg)
    {
            pthread_detach(pthread_self());
            pthread_mutex_lock(
    &NMutex);
            
    while (Number <= 0 )//等待主线程读入Number
                    pthread_cond_wait(&NCond, &NMutex);
            
    int Count = Number;
            
    int Sum = 1;
            
    for (int i = 1; i < Count; i++)
                    Sum 
    += i;
            cout 
    << "count by thread2 is " << Sum << endl;
            pthread_mutex_unlock(
    &NMutex);
            
    return NULL;
    }


    int main(int argc, char* argv[])
    {
            pthread_mutex_init(
    &NMutex, NULL);
            pthread_cond_init(
    &NCond, NULL);
            pthread_t p1, p2;
            pthread_create(
    &p1, NULL, thread1, NULL);
            pthread_create(
    &p2, NULL, thread2, NULL);


    //begin input
            pthread_mutex_lock(&NMutex);
               cout << "input a number ";
            cin 
    >> Number;
            pthread_mutex_unlock(
    &NMutex);
            pthread_cond_signal(
    &NCond);
    //end input

            pthread_exit(NULL);
    }

  • 相关阅读:
    宝塔跨域
    朵纳接口
    thinkphp5笔记
    phpstudy 配置域名访问无效
    如何在CentOS 下开放8080端口
    PHP:cURL error 60: SSL certificate unable to get local issuer certificate
    thinkphp6 项目使用composer安装好后提示控制器不存在:appcontrollerIndex
    DB2和MySql的区别是什么?
    idea 编辑工具
    Sublime text3最全快捷键清单
  • 原文地址:https://www.cnblogs.com/cy163/p/1285804.html
Copyright © 2011-2022 走看看