多个线程传递参数
Multiple threads passing parameter
有:
-
class cpu(){};
-
void operutable(){},cpu;此功能由线程执行。
void executable(){ while(run) { // for thread cout << "Printing the memory:" << endl; for (auto& t : map) { cout << t.first << " " << t.second << "n"; } } }
需要实例化5个线程,以执行可执行()函数:
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:线程构造函数?
有人可以给我一个理解此过程的例子。谢谢问候!
以下一些程序员dude 的评论,我还建议使用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 << "executable0n";
});
executables.emplace_back([](){
std::cout << "executable1n";
});
executables.emplace_back([](){
std::cout << "executable2n";
});
}
void create_and_exec_threads() {
for(const auto executable : executables) {
threads.emplace_back([=](){ executable(); });
}
for(auto& thread : threads) {
thread.join();
}
}
};
我们创建一个vector
,持有三个回调,该回调将用于初始化thread
S并在create_and_exec_threads
方法中启动它们。
请注意,与示例中的评论相反,创建一个带回电的std::thread
不仅将构造thread
,,而且还将立即启动它。/p>
此外,std::thread::join
方法不会启动thread
。它等待它完成。
相关文章:
- C++线程中,没有重载函数接受 X 参数
- C++ 中的线程不能使用参数
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- C++线程找不到函数作为参数(链接器)
- 如何将带有参数的方法传递给线程以执行?
- 为什么 beginthreadex 线程参数变量在父线程中没有更新
- 如何将参数传递给已经开始运行的线程
- 线程构造函数周围的可变参数模板包装器无法编译
- 线程函数中的c++参数更改
- 参数包推导不一致 int 和 int& 在可变参数模板化成员函数中创建运行成员函数的线程
- 线程函数参数的前向声明不起作用
- 带参数的线程调用库函数
- 错误:静态断言失败:std ::线程参数必须在转换为rvalues后不可行
- 从从可调用参数创建的线程对象参数移动构造 C++11 线程
- 错误 C2064:term 的计算结果不是采用 1 个参数的函数 - 关于线程的一些东西
- 通过将两个参数包的元素线程化为类型对来解压缩这两个参数包
- 提升线程:术语的计算结果不为 0 个参数
- C++线程错误 - 带有类参数的编译时错误
- 在 C++11 中,如何不将参数传递给线程
- 在单独的线程中使用参数启动成员函数