gpt4 book ai didi

multithreading - 如何将线程添加到std::vector

转载 作者:行者123 更新时间:2023-12-03 13:14:23 28 4
gpt4 key购买 nike

我正在尝试填补我的载体:

...    
auto f = std::bind(&ScheduledExecutor::complete_after, std::placeholders::_1, std::placeholders::_2);
threadPoolVector.push_back(std::thread(f, this, delay));
...

在将线程推送到向量之前,如何分离添加线程?

最佳答案

不要分离它们。您可以将std::shared_ptr用于vector中的线程:

std::vector<std::shared_ptr<std::thread>> threadPoolVector;
....
auto f = std::bind(&ScheduledExecutor::complete_after, std::placeholders::_1, std::placeholders::_2);
threadPoolVector.push_back(std::make_shared<std::thread>(f, this, delay));

如果由于某种原因不能使用共享指针,则可以使用 emplace_back() vector方法将线程移至vector:
std::vector<std::thread> threadPoolVector;
...
auto f = std::bind(&ScheduledExecutor::complete_after, std::placeholders::_1, std::placeholders::_2);
threadPoolVector.emplace_back(f, this, delay);

关于multithreading - 如何将线程添加到std::vector <std::thread>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29730378/

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