Run threads of a member function of a class in C ++

As the name says. Below is my code skeleton.

class CLASS { public: void A(); private: DWORD WINAPI B(LPVOID); }; void CLASS::A() { DWORD (WINAPI CLASS::*thread)(LPVOID) = &CLASS::B; ... CreateThread(NULL, 0, thread, &arg, 0, NULL); ... } 

function B needs CLASS member variables.
But when I compiled this, I have an error code. It "cannot convert argument 3 from" DWORD (__stdcall CLASS :: *) (LPVOID) "to" LPTHREAD_START_ROUTINE "or something like that.
I do not know if this is the same in the English environment.

Can anybody help?

+5
source share
3 answers

Seriously, use std :: thread (or boost :: thread if your compiler does not already support it):

 class CLASS { public: void A(); private: void B(your args go here); }; void CLASS::A() { boost::thread(&CLASS::B, this, your args go here); } 
+11
source

You must define your callback function as a static function if it is a member function!


Better Design: Define a Reusable Class!

From my previous answer : (with slight changes)

Even better would be to define a reusable class with a pure virtual function run() , which will be implemented by derived stream classes. Here's how it should be designed:

 //runnable is reusable class. All thread classes must derive from it! class runnable { public: virtual ~runnable() {} static DWORD WINAPI run_thread(LPVOID args) { runnable *prunnable = static_cast<runnable*>(args); return prunnable->run(); } protected: virtual DWORD run() = 0; //derived class must implement this! }; class Thread : public runnable //derived from runnable! { public: void newthread() { CreateThread(NULL, 0, &runnable::run_thread, this, 0, NULL); } protected: DWORD run() //implementing the virtual function! { /*.....your thread execution code.....*/ } } 
+10
source

You must make this member function static .

The problem is that each non-static member function has an implicit this parameter and that in fact what the compiler is trying to tell you, your member-member-member function is different from the one you expected.

Also see this answer to a close question .

+3
source

All Articles