<分区>
基本上我想做的是编写一个生成多个线程的 for 循环。线程必须多次调用某个函数。所以换句话说,我需要每个线程在不同的对象上调用相同的函数。我如何使用 std::thread C++ 库执行此操作?
<分区>
基本上我想做的是编写一个生成多个线程的 for 循环。线程必须多次调用某个函数。所以换句话说,我需要每个线程在不同的对象上调用相同的函数。我如何使用 std::thread C++ 库执行此操作?
最佳答案
您可以简单地在循环中创建线程,每次传递不同的参数。在此示例中,它们存储在 vector
中,以便稍后可以连接它们。
struct Foo {};
void bar(const Foo& f) { .... };
int main()
{
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i)
threads.push_back(std::thread(bar, Foo()));
// do some other stuff
// loop again to join the threads
for (auto& t : threads)
t.join();
}
关于c++ - 如何使用 std::thread C++ 生成调用相同函数的多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19675134/