for a university exercise I had to build a thread pool using classes. I started working on it but I encounterd some problems. My idea was to use ASYNC to generate the threads but compiler told me that the function that I had to provide to async should have been a static function. The problem was that if the main function of the thread was static also every variable had to be static and the threads can't reference all the variables mutex included. After some tries I came out with this solution but I don't know if it's good to proceed like that
class JobScheduler01 {
private:
unsigned int numOfThread;
std::vector<std::future<int>> pool;
//std::vector<std::thread> pool_thread;
std::list<Job> runningQueue;
std::list<Job> waitingQueue;
int ThreadMain(); // <- infinite loop
std::mutex m;
public:
JobScheduler01();
~JobScheduler01();
void Start(); // <- start all the threads
};
void JobScheduler01::Start() {
for(unsigned int i = 0; i < numOfThread; i++){
pool.push_back(std::async([this](){return ThreadMain();})); // <------ QUESTION
}
}
int JobScheduler01::ThreadMain() {
// main loop here
m.lock();
std::cout << "thread: " << std::this_thread::get_id() << "\n";
m.unlock();
return 0;
}
I created a lambda fuction that just start the main loop, but I'm not sure if it's right. Does this apporoach generate some sort of monsters? or is it ok? Which could be a better solution? Is it better to use async or to ue std::thread and join them in the destructor?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.