Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

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

I have the following class:

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

        void* threadStartRoutine( void *pThis );
}

I want to create a thread from inside starter() to run threadStartRoutine(). I get compile time errors with regard to the third argument, which should take the address of the start routine.

What would be the correct way to call pthread_create() to create a new thread that starts executing threadStartRoutine() ?

I have come across articles online that say that most compilers do not allow non-static member functions to be invoked using pthread_create(). Is this true? What is the reason behind this?

I am compiling my program on Linux-x64 using G++.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...