多个线程传递参数

Multiple threads passing parameter

本文关键字:参数 线程      更新时间:2023-10-16

有:

  • 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。它等待它完成。