我想创建一个包含一堆虚函数的类,这些函数在不同的事件上调用。我已经有了这个类但是如何将这些函数作为新线程启动?我可以设法仅在全局函数上执行此操作。我希望我的班级看起来像这样:
class Callbackk{
CallBack(){};
virtual ~Callback(){};
virtual void onSomething();
virtual void onElse(Someclass x);
virtual void onBum(Newclass nc);
}
当然每个函数都会被调用不同的参数,但我的想法是我希望这些函数无效并且能够接受一些参数。
使用:Visual Studio 2010
答案 0 :(得分:4)
不同的线程机制在这种情况下使用不同的语法。
我将提供boost::thread
库的示例。
显然,您必须将函数绑定到某个类实例才能调用它。这可以通过以下方式完成:
// Thread constructor is a template and accepts any object that models 'Callable'
// Note that the thread is automatically started after it's construction.
// So...
// This is the instance of your class, can possibly be some derived
// instance, whatever actually.
Callback* callback_instance;
// This construction would automatically start a new thread running the
// 'onElse' handler with the supplied arguments.
// Note that you may want to make 'x' a member of your thread controlling
// class to make thread suspending and other actions possible.
// You also may want to have something like 'std::vector<boost::thread>' created
// for your case.
boost::thread x(boost::bind(&Callback::onElse, callback_instance, ARGUMENTS));
答案 1 :(得分:0)
我的建议是在类中添加一些静态成员函数来执行此操作。例如,您可以添加一个名为onSomethingThread的静态成员函数,它通过函数onSomething执行您最初想要的相同操作。然后在函数onSomething中,您只需创建一个新线程并在其中运行onSomethingThread。