• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1232
  • Last Modified:

Pass member function to pthread_create

Apparently it's possible to pass a class member function to pthread_create if the member function is declared static.  At least, the following code compiles on gcc with no warnings:

class test {
      static void* threadf(void* args)
            cout << "testing..." << endl;
            return NULL;

int main() {
      test t;

      pthread_t thread;
      pthread_create(&thread, NULL, t.threadf, NULL);      
      pthread_join(thread, NULL);


Is this portable?  Is this allowed by the standard, or is gcc simply allowing this.
2 Solutions
Yes, this is allowed by standard. Static class method is actually global function, which can be accessed through class name. Non-static method has hidden "this" parameter. Both static method and global function don't have hidden parameter, this is the difference.
Deepu AbrahamR & D Engineering ManagerCommented:
Yes,static class methods are global hence it can be accessed.

class MyThread
static void* __stdcall ThreadProc(LPVOID lpVoid);

call this ThreadProc using _beginthread/ex/CreateThread..

HANDLE h_Thread;
h_Thread = (HANDLE)_beginthreadex(NULL,// Security
                  0,// Stack size - use default
                  ThreadProc,// Thread fn entry point -> note we have not used the class object here
                  (void*)this,// Param for thread any class object etc..if it is there else NULL
                  0,// Init flag
                  &nThreadID);// Thread address
Best Regards,
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now