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

时间:2012-10-15 21:06:08

标签: c++ multithreading templates c++11 lambda

我正在尝试使用此人的ThreadPool实现:https://github.com/progschj/ThreadPool

我在向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;
}

以下是我正在使用的内容:

#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;
        });
    }
}

示例代码的一部分是试图展示如何使用库...

汇编的输出是:

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.

当谈到模板化的东西时,我很无能为力......我不知道为什么上面的内容不起作用......任何人都有任何想法?

欢呼声

Jarrett的

1 个答案:

答案 0 :(得分:1)

您必须明确指定T,因为它不是参数列表的一部分,因此无法减少。

 pool.enqueue<TheType>(functor);

我无法猜测单独的片段应该是什么T.