gpt4 book ai didi

c++ - 带参数的类的 pthread 成员函数

转载 作者:太空宇宙 更新时间:2023-11-04 12:14:00 25 4
gpt4 key购买 nike

我使用本页底部的代码成功地将线程附加到类成员:http://www.tuxtips.org/?p=5 .

我不知道如何扩展代码来封装一个方法,例如 void* atom(void *inst) 其中 *inst 是一个包含的结构各种线程参数。具体来说,Netbeans 和我都不了解 example::*f 的定义位置以及它如何在 thread_maker 范围内有效。

最佳答案

我认为使用诸如 pthread(采用 c 回调)之类的东西的更好解决方案是创建一个包装函数,这样您就可以更容易地操作 boost::functions。这类似于 Using boost::bind() across C code, will it work? .

然后你可以简单地用 boost::bind 解决你的问题

class myClass
{
void atom(myStruct *data); // void return type to keep it similar to other code
// You could change it to a void* return type, but then you would need to change the boost::function declarations
};

boost::function<void(void)> function = boost::bind(&myClass::atom,&myClassInstance,&myStructInstance); //bind your function
boost::function<void(void)>* functionCopy = new boost::function<void(void)> (function); //create a copy on the heap

pthread_t id;
pthread_create(&id,NULL,&functionWrapper,functionCopy);

包装函数看起来像这样。

void functionWrapper(void* data)
{

boost::function<void(void)> *func = (boost::function<void(void)>* ) (data);
(*func)();
delete(func);
}

虽然此方法可能比手动传递数据要多一些工作,但它的可扩展性要高得多,可以轻松绑定(bind)任何内容并将其传递以启动您的线程。

编辑

最后一点:myClassInstance 和 myStructInstance 应该在堆上。如果它们在堆栈上,它们可能会在您的线程开始之前被删除。

关于c++ - 带参数的类的 pthread 成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8513254/

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