简体   繁体   中英

C++ - Thread Pool

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?

我建议尝试理解纯 c 中的线程池实现,就像这里这里的那些,然后开始使用 c++ 来替换(或在您的情况下实现)部分 c 代码(这可以是库代码,如 std::thread 、std::vector、std::mutex、智能指针或 C++ 语言功能,如引用、模板和 lambdas)。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM