基本上我想要做的是寫一個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