如何传递参数和函数给pthread_create

How to pass parameters and function to pthread_create

本文关键字:pthread create 函数 何传递 参数      更新时间:2023-10-16

好的,所以我正在看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);
    }
};