2

我正在使用 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

我哪里错了?

4

1 回答 1

1

boost::thread t[]你的和之间没有关系boost::thread_group threads;

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

而是这样做:

std::vector<boost::thread *> thread_ptrs;
// ...

    thread_ptrs.push_back(threads.create_thread(boost::bind(&InputThread)));

    // ...

    thread_ptrs[iterator].interrupt();

另外:名称“迭代器”通常用于类型并且迭代的价值很差。使用i此值或其他一些惯用名称。

于 2013-09-25T21:24:59.987 回答