【发布时间】:2015-09-15 16:42:50
【问题描述】:
您好,我不知道如何编写正确的队列绑定并执行传递给 OCRQueue::enqueue() 方法的 lambda 表达式
// the task queue
std::queue< std::function<void(OCRK*)> > tasks;
// add new work item to the pool
template<class F>
auto OCRQueue::enqueue(F&& f)
-> std::future<typename std::result_of<F(OCRK*)>::type>
{
using return_type = typename std::result_of<F(OCRK*)>::type;
auto task = std::make_shared< std::packaged_task<return_type()> >
(
// how to initialize this task so that it can be called
// task(OCRK*) passing the parameter to f(OCRK*)
std::bind
(
std::forward<F>(f)
)
);
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if (stop)
throw std::runtime_error("enqueue on stopped thread_pool");
// this fails because task does not accept parameters
tasks.emplace([task](OCRK* ocr){ task(ocr); });
}
condition.notify_one();
return res;
}
目前这无法在“auto task =”上编译,因为 f 需要一个 OCRK* 类型的参数:
错误 6 错误 C2064:术语不计算为采用 0 个参数的函数 C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xrefwrap 58 1 Skilja.PR.API
On: 1> d:\sourcecode\skilja\alpr\alpr\skilja.pr.api.native\OCRQueue.h(51) : 参见函数模板实例化 'std::shared_ptr> std::make_shared, std::_Bind &,>>(std::_Bind &,> &&)' 正在编译
预期的用法是这样的:
OCRQueue ocrPool(std::thread::hardware_concurrency());
auto work = [](OCRK* ocr)
{
return ocr->DoSomething();
};
future<DoSomethingResult> result = ocrPool.enqueue(work);
OCRK* 将在出队并在另一个线程中执行时传递给入队函数。
【问题讨论】:
标签: c++ multithreading c++11 lambda std