两个生产者,一个消费者,如何加锁和用条件变量

std::queue<int> q[2];        
//生产者,往队列放入数据
void peocesser(int i) {
    int count = 10;
    while (count > 0) 
    {
        q[i].push(count);
        count--;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));//等待10ms
    }
}
//消费者,从队列提取数据
void comsumer() {
    int data1,data2;
    while (! (q[0].empty() || q[1].empty())) 
    {
        data1 = q[0].front();
        data2 = q[1].front();
        q[0].pop();
        q[1].pop();
        printf("%d \n", (data1-data2) );
    }
}

int main() {
    std::thread t1(peocesser,0);
    std::thread t2(peocesser,1);
    std::thread t3(comsumer);
    t1.join();
    t2.join();
    t3.join();

    getchar();
    return 0;
}

你这个需要你说明下你希望达到的输出情况,你目前的代码因为sleep 10ms的问题,可能t3开始跑的时候q[0]和q[1]此时大小都为1,然后t3只计算一轮就已经q[0] 和q[1]执行pop()之后为0 导致跳出循环,故只会输出一个差值0然后t3线程就结束了(t1和t2都还没来得及插入剩下的9、8、7、6、5、4、3、2、1)。你这个t3线程需要都不为空时候就可以计算那么必定每次数据都是一致的了,也就是希望输出10个0;

#include <iostream>
#include <queue>
#include <thread>
#include <mutex>

std::mutex mtx;
std::queue<int> q[2];
bool pushend[2] = { false,false };
//生产者,往队列放入数据
void processer(int i) {
    int count = 10;
    while (count > 0) 
    {
        //printf("i=%d push %d \n", i, count);
        mtx.lock();
        q[i].push(count);
        count--;
        if (count == 0) {
            pushend[i] = true;
        }
        mtx.unlock();
        std::this_thread::sleep_for(std::chrono::milliseconds(10));//等待10ms
    }
}
//消费者,从队列提取数据
void consumer() {
    int data1, data2;

    while (1) {
        mtx.lock();
        if (!(q[0].empty() || q[1].empty())){
            data1 = q[0].front();
            data2 = q[1].front();
            q[0].pop();
            q[1].pop();
            printf("%d \n", (data1 - data2));
        }
        else {
            if (pushend[0] && pushend[1]) {
                mtx.unlock();
                break;
            }
        }
        mtx.unlock();
    }
}

int main() {
    std::thread t1(processer, 0);
    std::thread t2(processer, 1);
    std::thread t3(consumer);
    t1.join();
    t2.join();
    t3.join();

    getchar();
    return 0;
}