#2. Create a thread with class’s method.

In C/C++ starting the thread requires a static function as a starting address. Thus, in case that you want to invoke the thread with the target class’s method is a little bit complicated.

Here is a way that you can make it happen :D

First of, we got a very simple class name CSample and you want to create a thread with your own class method in order to let your thread has an access to your class memory space. In this example let’s say that function is named as targetFunctionToCall()

Now to create thread with this function simply you are required to have a static method to invoke this function first. I’ll name it with s_ prefix which stands for static.

In the implementation part we will create the thread with the static function s_targetFunctionToCall. And in this function it’ll invoke your targetFunctionToCall again. Here is what your header files would look like.

csample.h

   1: class CSample
   2: {
   3: public:
   4:     CSample();
   5:     virtual ~CSample();
   6: 
   7:     static void s_targetFunctionToCall(void *);
   8:     void targetFunctionToCall();
   9: };

 

csample.cpp

   1: #include "csample.h"
   2: 
   3: CSample::CSample()
   4: {
   5:     ::CreateThread(NULL, 0, (unsigned long (__stdcall *) (void *)) s_targetFunctionToCall, (void *) this, 0, NULL);
   6: }
   7: CSample::~CSample()
   8: {
   9: }
  10: void CSample::s_targetFunctionToCall(void * instance)
  11: {
  12:     ((CSample *) instance)->targetFunctionToCall();
  13:     ::ExitThread(0);
  14: }
  15: void CSample::targetFunctionToCall()
  16: {
  17:     // do your things
  18: }

 

As you can see the s_targetFunctionToCall redirect the code flow back to the old class by the instance parameter.

You can also modify your arguments since void * can pass anything to it, you may modify it with expansion with struct that packed everything you need inside and then pass it through.

Hope this will help :)

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.