简体   繁体   English

在线程池类中将函数指针作为函数模板发送

[英]send function pointer as function template in a threadpool class

I'm trying to use a ThreadPool implementation from this fellow: https://github.com/progschj/ThreadPool 我正在尝试使用来自这位研究员的ThreadPool实现: https : //github.com/progschj/ThreadPool

I'm having trouble adding 'functions' to the enqueue method...here is the implementation for the enqueue method below: 我在将'functions'添加到enqueue方法时遇到问题...这是下面的enqueue方法的实现:

// add new work item to the pool
template<class T, class F>
Result<T> ThreadPool::enqueue(F f)
{
    Result<T> res;
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        tasks.push_back(std::function<void()>(
        [f,res]()
        {
            CallAndSet<T,F>()(res, f);
        }));
    }
    condition.notify_one();
    return res;
}

Here's what I'm using: 这是我正在使用的:

#include "ThreadPool.h"
#include <stdio.h>
#include <iostream>

int main() {
    // create a thread pool of 4 worker threads
    ThreadPool pool(4);

    // queue a bunch of "work items"
    for(int i = 0; i < 8; ++i) {
        pool.enqueue([i] {
            std::cout << "hello " << i << std::endl;

            std::cout << "world " << i << std::endl;
        });
    }
}

It is part of the sample code that is trying to show how to use the library... 它是试图显示如何使用库的示例代码的一部分。

output from compilation is: 编译的输出为:

scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
scons: building associated VariantDir targets: build
g++ -o build/main.o -c -std=c++11 -pthread -Wall -g main.cpp
main.cpp: In function 'int main()':
main.cpp:15:7: error: no matching function for call to 'ThreadPool::enqueue(main()::<lambda()>)'
main.cpp:15:7: note: candidate is:
In file included from main.cpp:1:0:
ThreadPool.h:117:15: note: template<class T, class F> Result<T> ThreadPool::enqueue(F)
ThreadPool.h:117:15: note:   template argument deduction/substitution failed:
main.cpp:15:7: note:   couldn't deduce template parameter 'T'
scons: *** [build/main.o] Error 1
scons: building terminated because of errors.

I'm pretty clueless when it comes to templating stuff..I have no idea why the above won't work...anyone have any ideas? 在模板化方面,我一无所知。.我不知道为什么上面的方法行不通...任何人都有想法吗?

cheers 干杯

jarrett 耶雷特

You have to specify T explicitly as it is not part of the argument list and thus can not be reduced. 您必须明确指定T,因为它不是参数列表的一部分,因此无法减少。

 pool.enqueue<TheType>(functor);

I can not guess what T is supposed to be from the snippet alone. 我无法仅从代码片段中猜出T应该是什么。

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

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