【问题标题】:send function pointer as function template in a threadpool class在线程池类中将函数指针作为函数模板发送
【发布时间】:2012-10-15 21:06:08
【问题描述】:

我正在尝试使用这个家伙的 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.

我对模板化的东西一无所知..我不知道为什么上面的方法行不通...有人有什么想法吗?

干杯

贾勒特

【问题讨论】:

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


    【解决方案1】:

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

     pool.enqueue<TheType>(functor);
    

    我无法仅凭 sn-p 猜出 T 应该是什么。

    【讨论】:

    • 太棒了,做到了-谢谢@pmr!我刚刚将TheType 设置为void,它就像一个魅力
    • @Jarrett 只需确保查看文档并确定 void 是否真的是您想要的。同时提交一个错误。这当然可以改进。
    • 是的,显然Result 就像std::future,所以你可以指定(使用T)计算的“结果”的类应该是什么......我 认为 void 是有效的(也就是说,执行你发送的函数没有返回值)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    相关资源
    最近更新 更多