使用方法指针启动一个线程

Mic*_*ael 3 c++ methods multithreading member-function-pointers function-pointers

我正在尝试开发线程抽象(来自Windows API的POSIX线程和线程),我非常希望能够使用方法指针启动它们,而不是函数指针.

我想要做的是线程的抽象是一个带有纯虚方法"runThread"的类,它将被植入未来的线程类中.

我还不知道Windows线程,但要启动POSIX线程,您需要一个函数指针,而不是方法指针.而且我无法找到一种方法将方法与实例相关联,因此它可以作为一个函数工作.我可能只是找不到关键字(我一直在搜索很多),我认为它几乎是Boost :: Bind()所做的,所以它必须存在.

你能帮助我吗 ?

Ale*_* C. 9

不要这样做.使用boost::thread.

有了boost::thread你可以用签名的任何仿函数启动线程void(),所以你可以使用std::mem_funstd::bind1st,像

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));
Run Code Online (Sandbox Code Playgroud)

编辑:如果你真的想抽象POSIX线程(它并不难),你可以这样做(我给你留下pthread_attr的初始化)

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));
    }
};
Run Code Online (Sandbox Code Playgroud)

boost::thread便携,灵活且易于使用.