C++: Creating new thread using pthread_create, to run a class member function

前端 未结 4 1093
面向向阳花
面向向阳花 2020-12-22 04:53

I have the following class:

class A
{
    private:
        int starter()
        {
             //TO_DO: pthread_create()
        }

        void* threadStar         


        
相关标签:
4条回答
  • 2020-12-22 05:01

    Do you have a reason for using pthreads? c++11 is here, why not just use that:

    #include <iostream>
    #include <thread>
    
    void doWork()
    {
       while(true) 
       {
          // Do some work;
          sleep(1); // Rest
          std::cout << "hi from worker." << std::endl;
       }
    }
    
    int main(int, char**)
    {
    
      std::thread worker(&doWork);
      std::cout << "hello from main thread, the worker thread is busy." << std::endl;
      worker.join();
    
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-22 05:06

    Declare the threadStartRountine() as static:

    static void* threadStartRoutine( void *pThis );
    

    Otherwise, the type of threadStartRoutine() is:

    void* (A::*)(void*)
    

    which is not the type of function pointer that pthread_create() requires.

    0 讨论(0)
  • 2020-12-22 05:16

    Just use a normal function as a wrapper. As hjmd says, a static function is probably the nicest kind of normal function.

    0 讨论(0)
  • 2020-12-22 05:24

    If you insist on using the native pthreads interface, then you must provide an ordinary function as the entry point. A typical example:

    class A
    {
    private:
        int starter()
        {
            pthread_t thr;
            int res = pthread_create(&thr, NULL, a_starter, this);
            // ...
        }
    public:
        void run();
    };
    
    extern "C" void * a_starter(void * p)
    {
        A * a = reinterpret_cast<A*>(p);
        a->run();
        return NULL;
    }
    
    0 讨论(0)
提交回复
热议问题