(C ++ / Qt)线程运行太多

时间:2014-11-18 06:20:37

标签: c++ multithreading qt

在下面的示例程序中,我的意图是每秒打印五个相同的数字,但在实际运行时,数字打印得太多,有时大约10左右。我的代码有什么问题?

QTextStream qout(stdout);

class my_thread : public QThread
{
public:
    int n;

    my_thread()
    {
        n = 0;
    }

    void run()
    {
        while(n < 10)
        {
            qout << n++ << endl;
            sleep(1);
        }
    }
};

int main()
{
    enum { N_THREADS = 5 }; // N_THREADS = 2 with no problem...
    std::array<my_thread, N_THREADS> thread_array;
    for (std::array<my_thread, N_THREADS>::iterator it = thread_array.begin(); it != thread_array.end(); ++it)
    {
        it->start();
    }
    for (std::array<my_thread, N_THREADS>::iterator it = thread_array.begin(); it != thread_array.end(); ++it)
    {
        it->wait();
    }
    return 0;
}

修改

我发现一些有趣的行为,当N_THREADS为1或2时,我的程序运行正常;当N_THREADS等于3或更多时,它开始变得奇怪。为什么会这样?

0 个答案:

没有答案