如何传递参数和函数给pthread_create
How to pass parameters and function to pthread_create
好的,所以我正在看pthread_create的文档,我只是完全不明白如何做我想做的事情。
我想调用pthread_create,它将在pthread_t的结构体中传递。但是我传递给它的函数接受一个指向MyNode*的指针。如何将函数作为参数传递,并将"this"作为参数传递给那个函数。
//MyNode field and method in class file
pthread_t myTrd;
static void compute(MyNode* node);
////////////////////////////////////////////////////////////
//Actual code in header file below
static void MyNode::compute(*MyNode node){ //L61
//code
}
void MyNode::run(){ //run function in header file
pthread_create(&(this->thread),NULL,MyNode::compute, this);
}
结果:
myNode.cpp:61: error: 'static' may not be used when defining (as opposed to declaring) a static data member
myNode.cpp:61: error: 'int MyProjectGraph::MyNode::compute' is not a static member of 'class MyProjectGraph::MyNode'
myNode.cpp:61: error: expected primary-expression before 'node'
myNode.cpp:61: error: expected ',' or ';' before '{' token
myNode.cpp:134: error: expected `}' at end of input
传递给pthread_create()
的函数应该与原型匹配:
void *function(void *arg);
如果你的函数不匹配,你必须使用暴力和忽略(和强制转换)使函数指针可以接受-然后希望替代接口不会破坏任何东西。
让你的函数与规范匹配要好得多:
void *function(void *arg)
{
MyNode *mnp = (MyNode *)arg;
…
return 0;
}
返回可以返回一些更有意义的值,如果你有一个可用的,但返回一个null(你可能会写nullptr
,因为你主要使用c++)。
请注意,pthread_create()
本身通常是一个C函数,并且在传递给它的函数指针中期望C函数语义
为每个对象分配一个线程并不是一个好方法。我认为因为你把你的对象称为一个节点,所以你有一堆节点我想在线程中对它们做点什么。我通常这样做,这是一个经典的成语:
class Worker
{
struct ThreadStr
{
Worker * worker;
// put parameters here
MyNode * node;
};
public:
static void *StaticHandler(void *pvoid)
{
ThreadStr * data = (ThreadStr*)pvoid;
data->worker->Compute(data->node);
delete data;
return NULL;
}
void Compute(MyNode *node)
{
// whatever you want to compute on a node.
}
// start a thread to execute Worker::Compute(MyNode*)
void Run(MyNode *node)
{
ThreadStr * data = new ThreadStr();
data->worker = this;
data->node = node;
pthread_t threadId;
pthread_create(&threadId, NULL, Worker::StaticHandler, data);
}
};
相关文章:
- Using C++ CryptAPI:CNG Create CSR
- 错误:(-210:不支持的格式或格式组合)功能'create'中的硬件视频解码器不支持视频源
- 在 c++11 中为 pthread 设置调度参数
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- pthread只有在线程数量较少时才可以正常工作
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- pthread执行时间比顺序执行时间差
- 使用 -pthread 如何不违反 ODR 规则?
- 使用 pthread 的多线程
- QThread::create 似乎没有将参数传递给函数
- 销毁 pthread 互斥体和 C++ 中的取消初始化顺序
- 函数 AfxEndThread 中的读取访问冲突"pThread-> was nullptr"
- 锁定步进pthread互斥
- Pthread段错误,使用指向main中变量的指针
- pthread导致的内存泄漏
- GCC:--静态链接到pthread的整个存档配方在最近的GCC版本中停止工作
- 正确地编写一个类,并将pthread与vlc库和c++一起使用
- 为什么"non-standard syntax; use '&' to create a pointer to member"在 CTOR 中使用线程?
- QThread::create running on UI Thread
- 使用pthread Create创建两个类,并在cpp中相互访问