一段使用 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);
}

原文地址:https://www.cnblogs.com/cy163/p/1285804.html