简体   繁体   English

C++ - 线程池

[英]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.我的想法是使用 ASYNC 来生成线程,但编译器告诉我,我必须提供给 async 的函数应该是一个静态函数。 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.我创建了一个 lambda 函数来启动主循环,但我不确定它是否正确。 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?使用 async 还是使用 std::thread 并将它们加入析构函数更好?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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