mardi 6 janvier 2015

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?


Aucun commentaire:

Enregistrer un commentaire