我正在尝试在 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;
};