简体   繁体   English

C ++简单线程池

[英]C++ Simple Thread Pool

I am trying to implement a simple thread pool in c++ as follows: 我试图在C ++中实现一个简单的线程池,如下所示:

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 ). (您应该int size更改为size_t或者-如果您感觉很圣洁--vector 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. 它提供了一个请求复制的原型worker()对象,由于您提供了显式的默认构造函数,因此删除了隐式构造函数。

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

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