多线程传递参数

Multiple threads passing parameter

拥有:

需要实例化5个执行executable()函数的线程:

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