I have to use a C++ member function in pthread_create. Also, the member function needs to be able to get the argument.So, I have implemented a launcher function, which with help of a launcher object which stores the member function's address and the argument, will be able to do the desired.Is there a better/elegant way to do this?template <class T>class Launcher{public:    Launcher(T * obj, void * (T::*mfpt) (void *), void * arg) : myobj(obj), fpt(mfpt), myarg(arg) {}    ~Launcher() {}    void launch() { (*myobj.*fpt)(myarg);}private:    T* myobj;    void* myarg;    void * (T::*fpt) (void *); //Member function pointer };template <class T>void * LaunchMemberFunction(void * obj){    Launcher<T> * l = reinterpret_cast<Launcher<T>*>(obj);    l->launch();} Complete program and usage below:Link to Code#include <iostream>#include <pthread.h>class ScopedLock{public:    ScopedLock(pthread_mutex_t& mutex);    ~ScopedLock();    void lock();    void unlock();    bool isLocked();private:    pthread_mutex_t& _mutex;    bool _locked;};ScopedLock::ScopedLock(pthread_mutex_t& mutex) : _mutex(mutex) // references can only be initialized here{    //pthread_mutex_init(&_mutex, NULL);    //_mutex = mutex;    pthread_mutex_lock(&_mutex);    std::cout << acquired mutex\n;    _locked = true;}ScopedLock::~ScopedLock(){    pthread_mutex_unlock(&_mutex);    std::cout << destroyed mutex\n;    _locked = false;}void ScopedLock::lock(){    if (_locked) return;    pthread_mutex_lock(&_mutex);    _locked = true;}void ScopedLock::unlock(){    if (!_locked) return;    pthread_mutex_unlock(&_mutex);    _locked = false;}bool ScopedLock::isLocked(){    return _locked;}int count = 0;class Test{public:    Test() { pthread_mutex_init(&new_mutex, NULL); }    ~Test() {}    void * compute(void * data);private:    pthread_mutex_t new_mutex;};void * Test::compute(void * data){    int id = (int)data;    std::cout << my thread id: << id << | << pthread_self() <<        std::endl;    std::cout << before mutex count =  << count << | << id << std::endl;    ScopedLock sl(new_mutex);    sleep(3);    std::cout << after sleep mutex count =  << count << | << id << std::endl;    ++count;    std::cout << after Inc mutex count =  << count << | << id << std::endl;}template <class T>class Launcher{public:    Launcher(T * obj, void * (T::*mfpt) (void *), void * arg) : myobj(obj), fpt(mfpt), myarg(arg) {}    ~Launcher() {}    void launch() { (*myobj.*fpt)(myarg);}private:    T* myobj;    void* myarg;    void * (T::*fpt) (void *); //Member function pointer };template <class T>void * LaunchMemberFunction(void * obj){    Launcher<T> * l = reinterpret_cast<Launcher<T>*>(obj);    l->launch();}int main(){    pthread_t threads[3];    Launcher<Test> * larray[3];    Test t;    for (int i = 0; i < 3; ++i)    {        std::cout << In main: creating thread  << i << std::endl;        larray[i] = new Launcher<Test>(&t, &Test::compute, (void*)i);        std::cout << address of l is  << larray[i] << std::endl;        int rc = pthread_create(&threads[i], NULL, LaunchMemberFunction<Test>, larray[i]);        if (rc)        {            std::cout << Error: return code from pthread_create() is                       << rc <<  i=  << i << \n;            exit(-1);        }    }    for (int i = 0; i < 3; ++i)    {        pthread_join(threads[i], NULL);    }    std::cout << main thread count =  << count << std::endl;    //delete [] larray;    for (int i = 0; i < 3; ++i)    {        delete larray[i]; //cannot do delete [] larray here because larray has not been created by new    }    pthread_exit(NULL);}
Passing a member function in pthread_create
c++;multithreading
A few random points:I find it a little jarring that Launcher holds a T* as a member.  In general when writing/reviewing C or C++ I like to be able to quickly answer questions like who releases this object, and when?  By holding a potentially-dangling T* the way that you're doing, that ownership of resources becomes ambiguous, and handling deleting the objects in a safe way becomes tricky when you might have another thread working with it.  I would consider a reference-counted smart pointer like shared_ptr.It's also a bit weird to me that Launcher is tied to method pointers.  For more generality maybe Launcher should just be a template parameter that handles operator (), then you can provide multiple implementations for this, including one that calls a method pointer.  Maybe something like this:template <class T>void *thread_creation_routine(void *ptr){   // This thread now owns deleting the object...   // See pthread_create call below.   //   auto_ptr<T> arg(reinterpret_cast<T*>(ptr));   return (*arg)();}Then you could invoke it with something like:template <class T>class Launcher{    shared_ptr<T> m_ptr;    void *(T::*m_func)();public:    Launcher(shared_ptr<T> &ptr, void *(T::*func)()) : m_ptr(ptr), m_func(func) {}    void *operator ()()    {       return (*m_ptr.*m_func)();    }};Note in this usage, Launcher is only one functor that can be passed to thread_creation_routine.  You can envision others in the future.  (Say, C++0x lambda expressions -- although at that point I'd say maybe you should look into the new thread stuff that's in C++0x.)  Then finally you would tie it all together with something like this:class MyDemo{public:   void *SayHello()   {      cout << Hello, threaded world! << endl;      return 0;   }};int main(){   shared_ptr<MyDemo> myDemo(new MyDemo());   Launcher<MyDemo> *myLauncher(new Launcher<MyDemo>(myDemo, &MyDemo::SayHello));   pthread_t t;   int r;   if ((r=pthread_create(&t,                         NULL,                         thread_creation_routine<Launcher<MyDemo> >,                         myLauncher)))   {      // Failed to create the thread...      // Thread_creation_routine cannot take ownership of the launcher, so      // we delete it here.      //      delete myLauncher;      cerr << pthread_create failed with error  << r <<               ( << strerror(r) << ) << endl;      return r;   }   // NB: this could theoretically fail; error checking omitted...   //   pthread_join(t, NULL);   return 0;}Note the only weird thing here is the ownership of myLauncher's allocation.  If we succeeded in creating the thread, the thread routine deletes it, otherwise main will.  To make this sort of thing exception safe it might be advisable to wrap that allocation in RAII, but for this example it is not needed.Then notice with a quick rewrite of Launcher you can actually avoid the method pointer call entirely while still maintaining a lot of source code flexibility to change or re-use the thread creation routine:class Launcher2{    shared_ptr<MyDemo> m_ptr;public:    Launcher2(shared_ptr<MyDemo> &ptr) : m_ptr(ptr) {}    void *operator ()()    {       return m_ptr->SayHello();    }};You can imagine a compiler generating better code when using this launcher.  (Eg. the method call might be inlined into the thread creation routine.  Also, function pointer calls are typically not as efficient on modern CPUs as simply calling a function.)  In most cases this won't really make a difference, but if you had very frequent calls to something like this, it's a good thing to be aware of generally, and one of C++'s real strengths.  You can also imagine additional launchers which carry parameters for the callee, cleanly releasing any acquired resources they get deleted.Also: for your scoped locks...  It's rare, but pthread_mutex_lock can fail.  I'm not sure off the top of my head what those failure conditions may be, but you might want to do something for that case, like throw an error.Lastly...  I would re-iterate the earlier comment that maybe the C++0x thread support is right for you.  (To be honest I haven't looked into it all that much, so I don't know much about it myself.)  Failing that, maybe Boost.