Flave
Flave

Reputation: 77

Multiple threads passing parameter

Having:

Need to instantiate 5 threads that execute executable() function:

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

Now, I want to create:

 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.

How could I do? Initialize or using std:thread constructor?

Can someone give me an example to understand this process. Thanks & regards!

Upvotes: 1

Views: 138

Answers (1)

Fureeish
Fureeish

Reputation: 13434

Following Some programmer dude's comment, I would also advise using a standard container of 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();
        }
    }
};

We create a vector holding three callbacks, which will be used to initialise threads and start them inside create_and_exec_threads method.

Please do note that, as opposed to the comment in your example, creating a std::thread with a callback passed to its contructor will not only construct the thread, but also it will start it immediately.

Additionally, the std::thread::join method does not start the the thread. It waits for it to finish.

Upvotes: 1

Related Questions