c ++任意线程数,致命错误

时间:2015-04-03 16:46:00

标签: c++ multithreading visual-studio-2013

我有一个专门用于结构实例的函数,据我所知,它的线程是安全的。我有这些对象的向量,我想为每个实例创建一个线程。我试图按照以下方式进行,但是我得到了一个致命的错误。我试图弄清楚这是来自我设置线程的方式还是我正在线程化的函数。这是设置线程的合理方法吗?

void massThreadSectors(vector<skyImage>& images)
{
    int size = images.size();
    cout << size << endl << endl;
    vector<thread> vecThread(size);
    for (int i = 0; i < size; ++i)
    {
        vecThread.at(i) = thread(proccessSectors, images[i]);
    }
    for (int i = 0; i <= size; ++i) { vecThread.at(i).join(); cout << i << endl; }
}

调试输出为:

The thread 0x295c has exited with code 0 (0x0).
Microsoft Visual Studio C Runtime Library has detected a fatal error in cppImageProccess.exe.

Press Break to debug the program or Continue to terminate the program.

The thread 0x1e08 has exited with code 3 (0x3).
The thread 0x2824 has exited with code 3 (0x3).
The thread 0x2828 has exited with code 3 (0x3).
The thread 0x2834 has exited with code 3 (0x3).
The thread 0x2830 has exited with code 3 (0x3).
The program '[6120] cppImageProccess.exe' has exited with code 3 (0x3).

1 个答案:

答案 0 :(得分:3)

我的建议是尽量避免使用显式索引编写显式循环的习惯。在这种情况下,你当然可以:

vector<thread> vecThread(size);
for (int i = 0; i < size; ++i)
{
    vecThread.at(i) = thread(proccessSectors, images[i]);
}

我更喜欢这样写:

std::vector<thread> threads;

std::transform(images.begin(), images.end(), 
    std::back_inserter(threads),
    [](skyImage &i) { return thread(processSectors, i); });

同样,您加入的循环将使用std::for_each

完成
std::for_each(threads.begin(), threads.end(), [](thread &t) { t.join(); });

或者,您可以使用基于范围的for循环:

for (auto &i : images)
    threads.emplace_back(thread(processSectors, i));

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

无论哪种方式,循环都是“自动化的”,以至于很难弄错。