overexchange
overexchange

Reputation: 1

How to schedule a thread in C++11?

With the below code, I would like to place(push_back) the threads in a vector and launch the thread after every pop operation from vector.

#include <iostream>
#include <thread>
#include <algorithm>


int main() {
    std::vector<std::thread> workers;
    for(int i = 0; i < 10; ++i){
        workers.push_back(std::thread([](){
                std::cout << "Hi from thread\n";
            }));
    }

    std::cout << "Hi  from main!\n";
    std::for_each(workers.begin(), workers.end(), [](std::thread &th){
        th.join();
    });
    return 0;
}

But push_back() instruction does not actually convey that we are storing threads to launch it later. Because calling a constructor of class std::thread immediately launches thread.

In java, launch of thread can happen by placing in Queue(say) and dequeue it something like this:

-> searchQueue.enqueue( new SearchTask( record, this ) );

-> return searchQueue.size () > 0 ? (Runnable) searchQueue.removeFirst () : null ;

Because in java, thread gets launched after you invoke start() method of class Thread.

So, How do i perform similar operation in C++11?

Upvotes: 0

Views: 1650

Answers (1)

John Zwinck
John Zwinck

Reputation: 249153

You can store non-running threads plus the functions they will later run together:

typedef std::pair<std::thread, std::function<void()>> ThreadAndFunction;

std::vector<ThreadAndFunction> workers;

for(int i = 0; i < 10; ++i){
    ThreadAndFunction tf;
    workers.emplace_back(std::thread(), [](){
            std::cout << "Hi from thread\n";
        });
}

Then later, activate the threads using the functions:

for(int i = 0; i < 10; ++i){
    workers[i].first = std::thread(workers[i].second);
}

However, I don't think you're gaining much here. You could just store the functions without the empty threads at first, and create a vector of threads later.

Upvotes: 2

Related Questions