c++ - 使用方法指针启动线程

标签 c++ multithreading methods function-pointers pointer-to-member

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

我想做的是将线程抽象为一个带有纯虚方法“runThread”的类,并将其植入到 future 的线程类中。

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

你能帮帮我吗?

最佳答案

不要这样做。使用 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));

编辑:如果你真的想抽象 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));
    }
};

但是 boost::thread 是可移植的、灵活的并且使用起来非常简单。

关于c++ - 使用方法指针启动线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4503618/

相关文章:

c++ - 在 C++ 中将对象存储在另一个对象中的正确方法?

java - 为什么使用线程池时看不到性能提升?

php - C中的多线程程序 : calculating thread stack space

c# - 无法分配,因为它是方法组 C#?

c++ - 强制特定的类型定义类型

c++ - 在哪里可以找到用于机器人技术的 C/C++ Linux API?

C# 数组方法帮助

swift - 写一个实例方法提前那些分钟的时间

c++ - 嵌套数据结构中的STL排序

JavaFx - 不想出现结束对话框