0

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 function 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

Pijusn
  • 11,025
  • 7
  • 57
  • 76

2 Answers2

4

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));
Yippie-Ki-Yay
  • 22,026
  • 26
  • 90
  • 148
  • +1. For another example of using this technique http://stackoverflow.com/questions/86046/best-way-to-start-a-thread-as-a-member-of-a-c-class/86253#86253 – ravenspoint Jan 16 '11 at 15:45
0

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.

denfon
  • 11
  • 2