New thread on a class function
I want to make a class that contains a bunch virtual functions which are called on different events. I have the class already but how do I start those functions as new threads? I can manage to do this on global functions only. I want my class to look like this:
class Callbackk{
CallBack(){};
virtual ~Callback(){};
virtual void onSomething();
virtual void onElse(Someclass x);
virtual void onBum(Newclass nc);
}
of course each funct开发者_如何学Pythonion would be called with different parameters but the idea is that I want those functions to be void and be able to accept some arguments.
Using: Visual Studio 2010
Different threading mechanisms are using different syntax for this case.
I will supply the example for boost::thread
library.
Obviously, you have to bind your function to some class instance for it to be called. This can be accomplished the following way:
// 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));
My suggestion is that you add some static member functions in your class to do so. For example, you could add a static member function called onSomethingThread, which do the same things you want originally by the function onSomething. Then in the function onSomething, you simply create a new thread and run onSomethingThread in it.
精彩评论