Start thread using method pointer

I am trying to develop a thread abstraction (POSIX thread and thread from the Windows API), and I would really like it to be able to start them using a method pointer, not a function pointer.

What I would like to do is an abstraction of a thread, which is a class with a pure virtual "runThread" method that will be implanted into a future class with threads.

I don’t know about the Windows thread yet, but to start the POSIX thread you need a function pointer, not a method pointer. And I can’t find a way to associate the method with the instance so that it can work as a function. I probably just can't find the keywords (and I searched a lot), I think this is pretty much what Boost :: Bind () does, so it must exist.

Can you help me?

+3
source share
4 answers

Do not do that. Use boost::thread.

With the help of boost::threadyou can start threads with any signature functor void(), so you can use std::mem_funand std::bind1st, for example, in

struct MyAwesomeThread
{
    void operator()()
    {
        // Do something with the data
    }

    // Add constructors, and perhaps a way to get
    // a result back

private:
    // some data here
};

MyAwesomeThread t(parameters)
boost::thread(std::bind1st(std::mem_fun_ref(&t::operator()), t));

EDIT: If you really want to abstract POSIX threads (it's not complicated), you can do (I leave you with pthread_attr initialization)

class thread
{
    virtual void run() = 0; // private method

    static void run_thread_(void* ptr)
    {
        reinterpret_cast<thread*>(ptr)->run();
    }

    pthread_t thread_;
    pthread_attr_t attr_;

public:
    void launch() 
    {
        pthread_create(&thread_, &attr_, &::run_thread_, reinterpret_cast<void*>(this));
    }
};

but it boost::threadis portable, flexible and very easy to use.

+9
source

Boost.Thread. , , -, . .

class Thread {
public:
  void start() { start_thread(_work, this); }  // whatever call starts a thread

  void work() {} // does thread work

private:
  static void _work(void* param) {
    (reinterpret_cast<Thread*>(param))->work();
  }
}
+2

++ API . - boost:: thread ( API, ++). API- , , C, -, ( , boost:: bind).

+1

, , - ( Boost). , ( ), : SFML , . .

Ferruccio seems good! If the work () method is purely virtual, it can be implemented in any class that implements stream abstraction ... and this will work just fine, right? (I'm not quite sure if this happens, but according to my basic knowledge of C ++, I think it should be?)

0
source

Source: https://habr.com/ru/post/1781527/


All Articles