带有用户循环输入的C++多线程

问题描述 投票:0回答:1

我想完成一个程序,它可以在循环中接受用户输入并使用多线程进行一些计算,当用户想要退出时,循环退出。

ready
表示线程已准备好进行一些计算,
calculationDone
表示线程完成计算并通知主线程。
bExit
是我们可以退出循环的标志。

下面是我的代码:

#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
#include <sstream>
#include <string>

using namespace std;

mutex mtx;
condition_variable cv;
bool ready = false;
bool calculationDone = false;
bool bExit = false;

void print_id (int id) {
    do {
        unique_lock<mutex> lck(mtx);
        cv.wait(lck, [] { return ready || bExit; });
        if (bExit)
            break;
        // do some calculation
        cout << "thread" << id << endl;
        calculationDone = true;
        cv.notify_all();
    } while (!bExit);
}

int main ()
{
    std::thread threads[10];

    for (int i = 0; i < 10; ++i)
        threads[i] = thread(print_id, i);

    while (true) {
        cout << "Please input a number: ";
        string num;
        getline(cin, num);
        
        unique_lock<mutex> lck(mtx);
        ready = true;
        cv.notify_all();
        
        while (!calculationDone) cv.wait(lck);
        calculationDone = false;
        ready = false;
        
        string s;
        cout << "Do you want to input again: ";
        getline(cin, s);
        // if user input "N", exit the program
        if (s == "N") {
            bExit = true;
            cv.notify_all();
            break;
        }
    }

    for (auto& th : threads) th.join();

  return 0;
}

但是这个程序没有我想要的输出。我是多线程新手,希望得到您的帮助。谢谢。

c++ multithreading mutex condition-variable
1个回答
0
投票

您的线程和主线程之间存在竞争条件。您获得输入并设置

ready
。然后你
notify_all
。到目前为止还不错。

大家都醒了。第一个获得锁的人获胜。到目前为止仍然很好。该线程执行一些工作并完成计算。再次

notify_all
,然后松开锁和环。

此时,很可能下一个线程将获得锁,而不是主线程,但这是一场竞争。准备就绪,所以他再次计算。凉爽的。并在下一个线程中再次出现,等等。

这种非常手动的处理各种锁的方式将会一次又一次地困扰您。您最好编写某种工作队列并将工作分派到您的线程。

当然,你没有说出你想要的输出是什么以及你得到的输出是什么,所以我无法判断是否还有更多。

© www.soinside.com 2019 - 2024. All rights reserved.