基本上我想做的是编写一个生成多个线程的for循环。线程必须多次调用某个函数。换句话说,我需要每个线程在不同的对象上调用相同的函数。如何使用std :: thread c ++库?
答案 0 :(得分:6)
您可以简单地在循环中创建线程,每次传递不同的参数。在此示例中,它们存储在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();
}
答案 1 :(得分:0)
创建一个循环,每次迭代构造一个单独的线程对象,所有这些都具有相同的功能,但不同的对象作为参数。
答案 2 :(得分:0)
如果你想使用一些C ++ 11的东西以及利用std :: function + std :: bind的强大功能你可以尝试这样的事情:
#include <thread>
#include <functional>
#include <iostream>
#include <vector>
#include <memory>
typedef std::function<void()> RunningFunction;
class MyRunner
{
private:
MyRunner(const MyRunner&);
MyRunner& operator=(const MyRunner&);
std::vector<std::thread> _threads;
public:
MyRunner(uint32_t count, RunningFunction fn) : _threads()
{
_threads.reserve(count);
for (uint32_t i = 0; i < count; ++i)
_threads.emplace_back(fn);
}
void Join()
{
for (std::thread& t : _threads)
if (t.joinable())
t.join();
}
};
typedef std::shared_ptr<MyRunner> MyRunnerPtr;
class Foo
{
public:
void Bar(uint32_t arg)
{
std::cout << std::this_thread::get_id() << " arg = " << arg << std::endl;
}
};
int calcArg()
{
return rand() % UINT32_MAX;
}
int main(int argc, char** argv)
{
std::vector<Foo> objs;
for (uint32_t i = 0; i < 32; ++i)
objs.emplace_back(Foo());
std::vector<MyRunnerPtr> runners;
for (Foo& obj : objs)
{
const uint32_t someArg = calcArg();
runners.emplace_back(std::make_shared<MyRunner>(1, std::bind(&Foo::Bar, &obj, someArg)));
}
for (MyRunnerPtr& runner : runners)
runner->Join();
}