简体   繁体   中英

C++ Simple Thread Pool

I am trying to implement a simple thread pool in c++ as follows:

class worker {
public:
    worker();
    thread mThread;
private:
    void run();
};

worker::worker() {
    (this->mThread = thread(&worker::run, this)).detach();
}

class threadpool {
public:
    threadpool(int size);
    void addTask();
private:
    vector<worker> workers;
};

But when I add the constructor of threadpool:

threadpool::threadpool(int size) {
    this->workers = vector<worker>(size, worker());
}

I get an "attempting to reference a deleted function" error which as far as I know it means that somewhere in my code I am trying to copy a thread. Is there any way to solve this problem?

Smallest possible change is to:

threadpool::threadpool(int size) {
    this->workers = vector<worker>(size);
}

That said, initialiser lists are sweet.

threadpool::threadpool(int size)
  : workers{size}
{ }

(You should change from int size to size_t or - if you're feeling saintly - vector<worker>::size_type ).

It was the provision of a prototypical worker() object that requested copying, the implicit constructor for which was deleted because you'd provided an explicit default constructor.

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