我正在尝试创建一个具有这样的构造函数的ThreadPool类
ThreadPool(size_t numberOfThreads)
: workerThreads(numberOfThreads) {
workerThreads.reserve(numberOfThreads);
for(int i =0; i < numberOfThreads; i++) {
workerThreads.emplace_back(std::thread(&ThreadPool::doJob, this));
}
}
这无法为我编译,并引发以下错误
error: attempt to use a deleted function
__invoke(_VSTD::move(_VSTD::get<1>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...);
^
/Library/Developer/CommandLineTools/usr/include/c++/v1/thread:352:5: note: in instantiation of function template specialization
'std::__1::__thread_execute<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, void
(ThreadPool::*)(std::__1::function<void (char *, std::__1::list<std::__1::basic_string<char>,
std::__1::allocator<std::__1::basic_string<char> > > *)>), ThreadPool *, 2>' requested here
__thread_execute(*__p, _Index());
根据类似问题的其他答案,我也尝试这样做
workerThreads.emplace_back(std::thread(&ThreadPool::doJob, std::ref(*this)));
这也再现了同样的问题。我编译我的代码clang
c++14
在MacOS
这是完整的程序,其中复制了
class ThreadPool {
public:
ThreadPool(size_t numberOfThreads)
: workerThreads(numberOfThreads) {
for(int i =0; i < numberOfThreads; i++) {
workerThreads[i] = std::make_shared<std::thread>(std::thread(&ThreadPool::doJob, this));
}
}
ThreadPool(const ThreadPool& tp) {
workerThreads = tp.workerThreads;
jobQueue = tp.jobQueue;
}
std::function<void(char*, std::list<std::string>*)> getNextJob() {
if(!jobQueue.empty()) {
std::function<void(char*, std::list<std::string>*)> job = jobQueue.front();
jobQueue.pop_front();
return job;
}
throw std::runtime_error("No jobs to process, thread finished");
}
void addWork(std::function<void(char*, std::list<std::string>*)> job) {
lockListMutex.lock();
jobQueue.push_back(job);
lockListMutex.unlock();
}
private:
// performs actual work
void doJob(std::function<void(char*, std::list<std::string>*)> job) {
try {
lockListMutex.lock();
getNextJob();
lockListMutex.unlock();
} catch (std::runtime_error &e) {
}
}
// a vector containing worker threads
std::vector<std::shared_ptr<std::thread>> workerThreads;
// a queue for jobs
std::list<std::function<void(char*, std::list<std::string>*)>> jobQueue;
// a mutex for synchronized insertion and deletion from list
std::mutex lockListMutex;
};
int main(int argc, char *argv[]) {
int numThreads = 1;
ThreadPool* pool = new ThreadPool(numThreads);
}
由于doJob
成员函数的参数job
类型为std::function<void(char*, std::list<std::string>*)>
,因此在调用此函数时需要提供相应的参数。因此,以这种方式在新线程中调用此函数无效:
std::thread(&ThreadPool::doJob, this) // no argument for job passed
您可能需要提供一个参数,或者,因为可能应该从中将作业出队,所以从中jobQueue
删除job
参数doJob
:
void doJob()
{
... // dequeue job from jobQueue and execute it
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句