【发布时间】:2013-03-06 01:37:02
【问题描述】:
我正在尝试在 C++ 中创建一个 boost 线程,该线程可以重复用于运行具有不同数量和类型 args 的各种函数。
这可以用 C++11x 可变参数来完成吗?
在我的用例中,我不需要队列(如果线程很忙,那么方法就会失败),但如果需要实现这个“统一”功能,我会很不情愿地这样做。
我不明白如何使用 bind 或 lambda 处理统一,以便一个线程可以调用不同的函数,每个函数都有自己的不同数量和类型的 args。
我的想法大致如下:
class WorkThread
{
public:
WorkThread()
{
// create thread and bind runner to thread
}
~WorkThread()
{
// tell runner to exit and wait and reap the thread
}
template<typename F,typename ... Arguments>
void doWork(F func, Arguments... args)
{
if already busy
return false;
// set indication to runner that there is new work
// here: how to pass f and args to runner?
}
private:
void runner()
{
while ( ! time to quit )
{
wait for work
// here: how to get f and args from doWork? do I really need a queue? could wait on a variadic signal maybe?
f(args);
}
}
boost::thread* m_thread;
};
class ThreadPool
{
public:
template<typename F, typename ... Arguments>
bool doWork(F func,Arguments... args)
{
const int i = findAvailableWorkThread();
m_thread[i].doWork(f,args);
}
private:
// a pool of work threads m_thread;
};
【问题讨论】:
标签: c++ multithreading boost-thread variadic-templates