血刀老祖 2022-06-11 17:55 采纳率: 0%
浏览 45
已结题

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

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

  • 写回答

1条回答 默认 最新

  • 骑蜗牛追我 2022-06-12 16:48
    关注
    获得2.50元问题酬金

    你这个需要你说明下你希望达到的输出情况,你目前的代码因为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;
    }
    
    
    评论

报告相同问题?

问题事件

  • 系统已结题 6月20日
  • 赞助了问题酬金5元 6月12日
  • 创建了问题 6月11日

悬赏问题

  • ¥15 无法输出helloworld
  • ¥15 高通uboot 打印ubi init err 22
  • ¥20 PDF元数据中的XMP媒体管理属性
  • ¥15 R语言中lasso回归报错
  • ¥15 网站突然不能访问了,上午还好好的
  • ¥15 有没有dl可以帮弄”我去图书馆”秒选道具和积分
  • ¥15 semrush,SEO,内嵌网站,api
  • ¥15 Stata:为什么reghdfe后的因变量没有被发现识别啊
  • ¥15 振荡电路,ADS仿真
  • ¥15 关于#c语言#的问题,请各位专家解答!