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

  • 相关阅读:
    Vim配置及使用技巧
    终端提示符的配置
    Archlinux下i3wm与urxvt的配置
    Linux压缩命令
    Archlinux无线联网教程
    Archlinux安装和使用技巧
    Linux下硬盘分区
    Linux挂载
    Android中pullToRefresh使用
    SVN服务器搭建和使用教程
  • 原文地址:https://www.cnblogs.com/cy163/p/1285804.html
Copyright © 2011-2022 走看看