Jump to content
  • Advertisement
Sign in to follow this  
RojanShrestha

Extending an entire class to thread

This topic is 2558 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am trying to integrate a class to a thread.
In java I would do it like

class MyClass extends Thread
{}

This would execute all the member functions of MyClass in a thread.
How would I achieve similar functionality using pThread in C++

Share this post


Link to post
Share on other sites
Advertisement
Only reason Java requires inheritance is because it lacks free functions. Inheritance provides a single method run(), which is exactly the same as what other threading APIs do, including pthread.

This would execute all the member functions of MyClass in a thread.[/quote]

Far from it. Class that extends thread is mostly unrelated to threading and is merely required scaffolding due to how Java works.

What gets executed in a thread is determined solely by how it's called. In Java, methods that are called from a thread that is was created with Thread.start() (which invokes Thread.run()) will run on that particular thread.

In pthreads, the equivalent would be:void MyClassRun(void * ptr) {
printf("Hello from thread");
}
...
pthread_create( &t, NULL, MyClassRun, NULL);


In order to deal with classes, a bit of indirection is required:class Thread {
virtual ~Thread();
virtual void run();
};

...

void run_in_a_thread(void * ptr) {
Thread * ptr = (Thread*)ptr;
ptr->run();
}

...

MyClass * mc = new MyClass(); // something that extends thread and implements run();
pthread_create( &t, NULL, run_in_a_thread, mc);

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!