使用 std::vector<std::future<int>> 和 std::async 启动几个线程时中止

Abort() when starting up a few threads with std::vector<std::future<int>> and std::async

本文关键字:std gt lt 几个 线程 future vector int 使用 启动 async      更新时间:2023-10-16

我正在使用 4 个线程使用thread_local内存池创建一些对象。

我正在使用std::vector<std::future<int>>std::async(std::launch::async, function);来调度线程,并与t.getstd::for_each以恢复它们的价值。代码如下:

struct GameObject
{
int x_, y_, z_;
int m_cost;
GameObject() = default;
GameObject(int x, int y, int z, int cost)
: x_(x), y_(y), z_(z), m_cost(cost)
{}
};
struct Elf : GameObject
{
Elf() = default;
Elf(int x, int y, int z, int cost)
: GameObject(x, y, z, cost)
{
std::cout << "Elf created" << 'n';
}
~Elf() noexcept
{
std::cout << "Elf destroyed" << 'n';
}
std::string m_cry = "nA hymn for Gandalfn";
};
struct Dwarf : GameObject
{
Dwarf() = default;
Dwarf(int x, int y, int z, int cost)
: GameObject(x, y, z, cost)
{
std::cout << "dwarf created" << 'n';
}
~Dwarf() noexcept
{
std::cout << "dwarf destroyed" << 'n';
}
std::string m_cry = "nFind more cheer in a graveyardn";
};

int elvenFunc()
{
thread_local ObjectPool<Elf> elvenPool{ 229 };
for (int i = 0; i < elvenPool.getSize(); ++i)
{
Elf* elf = elvenPool.construct(i, i + 1, i + 2, 100);
std::cout << elf->m_cry << 'n';
elvenPool.destroy(elf);
}
thread_local std::promise<int> pr;
pr.set_value(rand());
return 1024;
}
int dwarvenFunc()
{
thread_local ObjectPool<Dwarf> dwarvenPool{ 256 };
for (int i = 0; i < dwarvenPool.getSize(); ++i)
{
Dwarf* dwarf = dwarvenPool.construct(i - 1, i - 2, i - 3, 100);
std::cout << dwarf->m_cry << 'n';
dwarvenPool.destroy(dwarf);
}
thread_local std::promise<int> pr;
pr.set_value(rand());
return 2048;
}

int main()
{
std::ios_base::sync_with_stdio(false);
srand(time(0));
std::vector<std::future<int>> vec{ 4 };
vec.emplace_back(std::async(std::launch::async, elvenFunc));
vec.emplace_back(std::async(std::launch::async, elvenFunc));
vec.emplace_back(std::async(std::launch::async, dwarvenFunc));
vec.emplace_back(std::async(std::launch::async, dwarvenFunc));
int term = 0;
try
{
std::for_each(std::execution::par, vec.begin(), vec.end(), [&term](std::future<int>& t)
{
auto ret = t.get();
std::cout << "thread brought me " << ret << 'n';
term += ret;
});
}
catch (const std::exception& ex)
{
std::cout << ex.what() << 'n';
}
std::cout << "Final word = " << term << 'n';
}

(constructdestroy在内部调用allocatedeallocate。我从终端获得了很多预期的输出,但是在某个地方abort被调用并且程序无法正常完成。我找不到为什么。我相信以 std::async 启动的线程的t.get()调用也会自动调用.join对吗?

使用 C++17 和 Visual Studio 2017。我做错了什么?

你有未定义的行为。您在无效的未来调用get。您的期货向量有前 4 个项目作为空future。 仅当future::valid返回 true 时,才能调用get

你怎么看这句话

std::vector<std::future<int>> vec{ 4 };

是否 ?

默认构造函数。构造一个没有共享状态的 std::future。 构造后,valid(( == 假。

在这里,您可以阅读调用future::get时会发生什么:

如果在调用此行为之前 valid(( 为 false,则行为未定义 功能。