具有:
void executable(){
while(run) { // for thread
cout << "Printing the memory:" << endl;
for (auto& t : map) {
cout << t.first << " " << t.second << "\n";
}
}
}
需要实例化5个执行execute()函数的线程:
for (int i = 0; i < 5; i++)
threads.push_back(thread(&CPU::executable, this)); //creating threads
cout << "Synchronizing all threads...\n";
for (auto& th : threads) th.join(); //waits for all of them to finish
现在,我要创建:
void executable0 () {
while(run) {
cout << "Printing the memory:" << endl;
for (auto& t : map) {
cout << t.first << " " << t.second << "\n";
}
}
}
void executable1 () {....}
to executable4() {....} // using that five threads that I`ve done above.
我该怎么办? 初始化或使用std:thread构造函数吗?
有人可以给我一个例子来理解这个过程。
感谢和问候!
最佳答案
遵循之后,一些程序员对的评论提出了建议,我也建议您使用标准容器std::function
:
#include <iostream>
#include <thread>
#include <map>
#include <functional>
#include <vector>
class CPU {
std::vector<std::function<void()>> executables{};
std::vector<std::thread> threads{};
public:
CPU() {
executables.emplace_back([](){
std::cout << "executable0\n";
});
executables.emplace_back([](){
std::cout << "executable1\n";
});
executables.emplace_back([](){
std::cout << "executable2\n";
});
}
void create_and_exec_threads() {
for(const auto executable : executables) {
threads.emplace_back([=](){ executable(); });
}
for(auto& thread : threads) {
thread.join();
}
}
};
我们创建一个包含三个回调的
vector
,这些回调将用于初始化thread
并在create_and_exec_threads
方法中启动它们。请注意,与示例中的注释相反,使用传递给回调函数的回调函数创建
std::thread
不仅会构造thread
,还会立即启动它。此外,
std::thread::join
方法不会启动thread
。它等待它完成。关于c++ - 多线程传递参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54782264/