gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:47:02 25 4
gpt4 key购买 nike

我正在尝试开发线程抽象(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com