基本上我想要做的是写一个for循环,产生多个线程。线程必须多次调用某个函数。换句话说,我需要每个线程在不同的对象上调用相同的函数。我如何使用std :: thread C++库来做到这一点?如何产生使用std :: thread调用相同函数的多个线程C++
3
A
回答
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();
}
0
做一个循环,每次迭代构造一个单独的线程对象,所有的函数都具有相同的功能,但不同的对象作为参数。
0
如果你想使用一些C++ 11的东西,以及利用性病的大国::功能+的std ::绑定你可以尝试这样的事:
#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();
}
相关问题
- 1. 多线程调用相同的函数
- 2. 如何使用C#中调用相同方法的多线程?
- 3. 使用std :: thread将多个线程的数组组合在一起使用std :: thread
- 4. 多线程无法正常使用std :: thread(C++ 11)
- 5. C++:如何在UI线程和工作者std :: thread之间使用std :: condition_variable
- 6. 参考C++多线程函数调用
- 7. 在C++中自动调用std :: thread的函数11
- 8. std :: thread在主线程上执行回调函数
- 9. 使用静态函数在C++中使用TBB产生线程
- 10. 如何处理调用相同函数的多个Ajax调用?
- 11. 如何使用带引用的函数指针创建std :: thread?
- 12. JavaScript/D3:“相同”的函数调用产生不同的结果?
- 13. 使用相同变量的两个线程产生问题
- 14. 做一个java函数调用产生新的线程执行?
- 15. 使用线程在python中调用多个C++函数
- 16. 多线程调用相同的函数是否安全?
- 17. 错误C2280:'std :: thread :: thread(const std :: thread&)':尝试引用已删除的函数
- 18. 多个线程在C调用相同的方法#
- 19. 多个线程可以加入相同的boost :: thread吗?
- 20. 使用std :: thread与std :: mutex
- 21. C++从它的线程函数引用boost :: thread
- 22. 多线程函数调用
- 23. 如何在UWP中的对象的成员函数内使用std :: thread C++/CX
- 24. OpenMP,MPI,POSIX线程,std :: thread,boost :: thread如何关联?
- 25. 如何让C++ 11线程运行多个不同的函数?
- 26. 使用graphics.h的小型C++游戏,一次调用多个函数? (多线程?)
- 27. 使用相同AJAX函数的多个AJAX调用
- 28. 'std :: thread :: thread':没有重载的函数需要7个参数
- 29. C++的std ::异步不会产生一个新的线程
- 30. XCode std :: thread C++
会如果你可以提供一些你已经尝试过的东西,那么这会有所帮助。 – kfsone