在我的 C++ 应用程序中,我有 2 个线程:(i)主线程,(ii)后台线程。我有一个类定义为:
class helper
{
public:
bool login(const string& username, const string& password);
void logout();
private:
bool loginInternal(const string& username, const string& password);
void logoutInternal();
}
在主线程上调用 helper::login() 和 helper::logout() 函数(以及具有各种返回类型和 # of params 和 param 类型的其他几个成员函数)。在这些函数的实现中,对应的内部函数要入队,后台线程按照入队的顺序调用这些内部函数。所以是这样的:
bool helper::login(const string& username, const string& password)
{
queue.push_back(boost::bind(&helper::loginInternal, this, username, password));
}
void helper::logout()
{
queue.push_back(boost::bind(&helper::logoutInternal, this));
}
后台线程一直在运行,等待队列填满,一旦填满,这个后台线程就会开始调用队列中的函数:
queue.front()();
queue.pop_front();
那么问题来了,我该如何定义这样的队列呢?
deque<???> queue;
该队列的数据类型可能是什么,以便它可以在同一个队列中保存具有不同签名的回调函数?
编辑:这是解决方案(感谢 J. Calleja):
typedef boost::function<void ()> Command;
deque<Command> queue;
然后像这样调用仿函数:
// Execute the command at the front
Command cmd = queue.front();
cmd();
// remove the executed command from the queue
queue.pop_front();