use*_*095 3 c++ multithreading c++11 stdthread
基本上我想要做的是编写一个生成多个线程的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();
}
Run Code Online (Sandbox Code Playgroud)