gpt4 book ai didi

c++任意线程数, fatal error

转载 作者:行者123 更新时间:2023-11-28 00:17:19 24 4
gpt4 key购买 nike

我有一个专门作用于结构实例的函数,据我所知它是线程安全的。我有这些对象的 vector ,我想为每个实例创建一个线程。我试图按如下方式进行,但出现 fatal error 。我正在尝试确定这是来 self 设置线程的方式还是我正在处理的函数。这是设置线程的合理方法吗?

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).

最佳答案

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

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();

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

关于c++任意线程数, fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29436278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com