3

After searching trough the forum, i came across some answers nevertheles I could not get a clear answer to how to run a static method in a new thread in c++. My main concern is what is the best way to start a thread?(Is it working also from inside of another thread?) which header is better to use? thread.h, pthread.h?

I would like to create a new thread(when a given method is called) and call inside this thread another function... Any hints how I could approach this issue?

Thank you guys very much in advance!

user1679802
  • 167
  • 1
  • 2
  • 11
  • This is OS specific, or at least it will be until std::thread is implemented by all compilers. (It's part of C++11). Which OS are you using? – Benj Oct 02 '12 at 11:08
  • Looks like you should start from the basics of C++ language to understand what keyword "static" means. – Sergei Nikulov Oct 02 '12 at 11:24
  • BTW, here the example how to pass static member to thread with explanation http://stackoverflow.com/questions/7761527/passing-static-method-as-argument-no-address-of-operator-required – Sergei Nikulov Oct 02 '12 at 11:37

3 Answers3

7

There is no problem to run static member function in thread. Just use std::thread the same way as for free function:

#include <thread>

class Threaded
{
public:

   static void thread_func() {}

};

int main()
{
    std::thread t(Threaded::thread_func);
    t.join();
    return 0;
}

Of course, starting thread will work from any other thread as well. With C++11 standard compliant compiler you shall use #include <thread>. Otherwise take a look at boost::thread. It's usage is similar.

Rost
  • 8,779
  • 28
  • 50
2

Assuming for example your static function has two parameters:

#include <boost/thread/thread.hpp>

void launchThread()
{
    boost::thread t( &MyClass::MyStaticFunction, arg1, arg2 );
}

This will require linking to the Boost.Thread library.

usta
  • 6,699
  • 3
  • 22
  • 39
1

The best OOPs way of doing this would be: Define an entry point (entryPoint()) which will call a member function(myThreadproc()). The entry point will start the thread and call myThreadproc. Then you can access all the member variables and methods.

myClassA.h

class A
{
   static void *entryPoint(void *arg);
   void myThreadproc();
   void myfoo1();
   void myfoo2();
}

myClassA.cpp

void *A::entryPoint(void *arg)
{
   A *thisClass = (A *)arg;
   thisClass-> myThreadproc();
}

void A::myThreadproc()
{
       //Now this function is running in the thread..
       myfoo1();
       myfoo2();
}

Now you can create the thread like this:

int main()
{
   pthread_t thread_id; 
   pthread_create(&thread_id,NULL,(A::entryPoint),new A());
   //Wait for the thread
   return 0;
}
user739711
  • 1,842
  • 1
  • 25
  • 30