多线程输出奇偶数

#include <pthread.h>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
using namespace std;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER; 
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
bool flag = false;
int i = 0;
void* PrintA(void *arg){
    while(1){
        pthread_mutex_lock(&qlock);
        pthread_cond_wait(&qready,&qlock);
        cout << "A = " << i << endl;
        i ++;
        pthread_mutex_unlock(&qlock);
        flag = false;
        if(i >= 100){
            break;
        }
    }
}
void* PrintB(void *arg){
    while(1){
        if(i >= 100)    break;
        if(flag == true)    continue;
        pthread_mutex_lock(&qlock);
        cout << "B = " << i << endl;
        i ++;
        pthread_mutex_unlock(&qlock);
        if(flag == false){
        flag = true;
        pthread_cond_signal(&qready);
        }
    }
}
int main(){
    pthread_t tid1, tid2;
    int iRet = pthread_create(&tid1, NULL, PrintA, NULL);
    iRet = pthread_create(&tid2, NULL, PrintB, NULL);
    void * retval;
    iRet = pthread_join(tid1, &retval);
    iRet = pthread_join(tid2, &retval);
    return 0;
}
原文地址:https://www.cnblogs.com/qq136155330/p/12735314.html