多线程传递参数

时间:2019-02-20 08:53:34

标签: c++ multithreading instance-variables

具有:

  • 类CPU(){};

  • void可执行文件(){},在CPU内部;该功能由线程执行。

    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构造函数

有人可以给我一个例子来理解这个过程。 谢谢与问候!

1 个答案:

答案 0 :(得分:1)

一些程序员哥的评论之后,我还建议您使用标准容器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。等待它完成。