多个线程传递参数

问题描述 投票:1回答:1

有:

  • class CPU(){};
  • void可执行文件(){},在CPU内部;这个函数由一个线程执行。 void executable(){ while(run) { // for thread cout << "Printing the memory:" << endl; for (auto& t : map) { cout << t.first << " " << t.second << "\n"; } } }

需要实例化执行executable()函数的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:thread构造函数?

有人能给我一个例子来理解这个过程。感谢和问候!

c++ multithreading instance-variables
1个回答
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,它将用于初始化threads并在create_and_exec_threads方法中启动它们。

请注意,与示例中的注释相反,创建带有回调传递给其构造函数的std::thread不仅会构造thread,而且还会立即启动它。

此外,std::thread::join方法不启动thread。它等待它完成。

© www.soinside.com 2019 - 2024. All rights reserved.