我试图创建一个可以运行未知类中的函数的线程池。我不希望创建非成员作为代理。
我设法创建了一个工作池和workerthread类以及一个任务结构,所有这些都是模板。
// ThreadPool.h
/* Threadpool creates N WorkerThreads (each worker has a ptr to the creating pool),
these block until a task is ready then call ThreadPool::doTask() */
template<class T>
struct Task {
Task() : func(0), inst(0) { }
Task(boost::function<void(T*)> function, T* instance) : func(0), inst(0) {
func = function;
inst = instance;
}
void operator()() {
Task::func(inst);
}
T* inst;
boost::function<void(T*)> func;
};
template<class T>
class ThreadPool {
template<class T> friend class WorkerThread;
public:
void addTask(Task<T> task) {
... // Some stuff
}
bool doTask() {
Task<T> task;
... // Gets a task from std::queue
// Check the task actually exists!
if(task.func && task.inst) {
// Do the task
(task)();
}
}
private:
std::queue<Task<T>> mTasks;
};
照原样,如果我确定ThreadPool和Task的类,则此代码有效。但我希望能够调用未知类类型的成员。我曾经考虑过使用无效的ptr,但是找不到将其转换为有效实例ptr的方法。我也研究了boost::mem_fun,但是很难真正掌握它。
我已经简要了解了C++ 0x,并且据我了解,它应该使解决我的问题更加容易,但是我想在那之前(如果可能)解决这个问题。
最佳答案
为什么要使用T *而不是boost::function<void ()>
呢?
这样,您可以使用自由函数和成员函数,并且可以简化代码。
X类实例上的成员任务可以像这样排队:
poll.add(boost::bind(&X::member, x_instance, other_arguments));
在代码中没有强制转换和模板。
更新:
使用boost::function而不是Task类。然后,您只需要跟踪实例并适当地调用它们即可。例如:
class TaskQueue {
std::deque<boost::function<void ()> > m_tasks;
public:
void add(boost::function<void ()> const& f) { m_tasks.push_back(f); }
bool has_task() const { return !m_tasks.empty(); }
void do_task() {
m_tasks.front()();
m_tasks.pop_front();
}
};
int example_enqueue(TaskQueue* tq) {
boost::shared_ptr<RandomClass> rc(new RandomClass);
tq->add(boost::bind(&RandomClass::method, rc, arg_1, arg_whatever));
}
请注意,通过将此方法与boost::shared_ptr结合使用,如果该函数超出范围(如果它是最后一个引用),则会自动破坏对象。这使生活更加轻松。
关于c++ - 存储并稍后调用未知类的成员函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6096860/