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);
    }

  • 相关阅读:
    网络兼职轻松赚
    微信H5支付demo
    支付宝H5支付demo
    笔记本安装SSD固态硬盘详细的优化设置
    JQuery的AJAX
    第二次面试
    存储过程的总结
    SQl数据操作和查询
    面对考试毫无畏惧的SSH
    掷骰子-IOS新手项目练习(抱歉,由于个人原因,图片没显示,要源码的项目私聊)
  • 原文地址:https://www.cnblogs.com/cy163/p/1285804.html
Copyright © 2011-2022 走看看