【问题标题】:boost thread_group infinite loopboost thread_group 无限循环
【发布时间】:2013-10-01 15:56:29
【问题描述】:

我正在使用 boost 并尝试创建一个基本的 thread_group 来执行他们的任务并退出。这是我的代码的样子:

boost::thread_group threads;
void InputThread()
{
    int counter = 0;

    while(1)
    {
        cout << "iteration #" << ++counter << " Press Enter to stop" << endl;

        try
        {
            boost::this_thread::sleep(boost::posix_time::milliseconds(500));
        }
        catch(boost::thread_interrupted&)
        {
            cout << "Thread is stopped" << endl;
            return;
        }
    }
}

int main()
{
    int iterator;
    char key_pressed;
    boost::thread t[NUM_THREADS];

    for(iterator = 0; iterator < NUM_THREADS; iterator++)
    {
        threads.create_thread(boost::bind(&InputThread)) ;
        cout << "iterator is: " << iterator << endl;

           // Wait for Enter to be pressed      
        cin.get(key_pressed);

        // Ask thread to stop
        t[iterator].interrupt();

    }
    // Join all threads
    threads.join_all();

    return 0;
}

我从两个线程开始,在两个线程都完成工作后陷入无限循环。如下所示:

iterator is: 0
iteration #1 Press Enter to stop
iteration #2 Press Enter to stop

iterator is: 1
iteration #1 Press Enter to stop
iteration #3 Press Enter to stop
iteration #2 Press Enter to stop

iteration #4 Press Enter to stop
iteration #3 Press Enter to stop
iteration #5 Press Enter to stop
iteration #4 Press Enter to stop
iteration #6 Press Enter to stop
iteration #5 Press Enter to stop
iteration #7 Press Enter to stop
^C

我哪里出错了?

【问题讨论】:

    标签: c++ boost infinite-loop boost-thread threadgroup


    【解决方案1】:

    您的boost::thread t[]boost::thread_group threads; 之间没有任何关系。

    所以t[iterator].interrupt();threads.create_thread(boost::bind(&amp;InputThread)) ; 产生的线程没有影响。

    改为:

    std::vector<boost::thread *> thread_ptrs;
    // ...
    
        thread_ptrs.push_back(threads.create_thread(boost::bind(&InputThread)));
    
        // ...
    
        thread_ptrs[iterator].interrupt();
    

    除此之外:“迭代器”这个名称通常用于类型,并且会产生不好的迭代值。使用 i 或其他惯用名称来表示此值。

    【讨论】:

    • 谢谢,这解决了问题。不过,我需要更好地了解 thread_group。
    • @user2816953 如果您对答案感到满意,请相应地投票和/或接受答案。
    • 我已经接受了答案,但仍然没有足够的声誉来投票。我前两天刚注册。当我到达那里时,我会通过投票来回报你的回答:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 2012-04-11
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多