c++ - pthread_create C++ 中的无效转换

标签 c++ multithreading function-pointers

<分区>

我有一个名为 qwerty 的类和一个名为 compute_ans 的函数,它接受一个空指针并返回一个空指针。现在,当我尝试编译时,以下语句会引发错误

pthread_create (thread_a, NULL, compute_ans, (void*) struct_left);

函数的定义是void* compute_ans (void* struct_input)

错误是

cannot convert ‘qwerty::compute_ans’ from type ‘void* (qwerty::)(void*)’ to type ‘void* ()(void)’*

最佳答案

不能将指向非静态成员函数的指针转换为指向函数的指针,C++ 不允许这样做。原因是成员函数采用隐式 this 指针作为参数。从本质上讲,这会将您的函数签名更改为类似于 void* compute_ans(qwerty*, void*)。为了将函数传递给 pthread_create,您需要将成员函数设为静态。

class qwerty
{
public:
    // ... other member functions and variables ...

    // thread start function
    static void* compute_ans(void*);
};

如果您不能将其设为静态成员函数,则需要将指向 qwerty 对象的指针传递给线程启动函数。查看问题中的代码,您还需要将其他数据传递给线程函数。为此,您可以使用包含所有必要数据的附加数据结构,并将指针传递给它。

class qwerty;  // forward declaration

// Structure passed to pthread_create and our helper function
struct thread_data
{
    qwerty* qptr;   // pointer to qwerty object
    void*   data;   // pointer to other data. change void to your data type.
};

class qwerty
{
public:
    // thread start function
    static void* start_compute_ans(void* param)
    {
        // get a pointer to the thread data
        thread_data* tdata = static_cast<thread_data*>(param);

        // Call the real compute_ans
        tdata->qptr->compute_ans(tdata->data);

        // Delete the data (use an appropriate smart pointer if possible)
        delete tdata;

        return NULL;
    }

    // the real 
    void compute_ans(void*)
    {
        // do stuff here
    }
};

// Create our thread startup data
thread_data* tdata = new thread_data();
tdata->qptr = qwerty_pointer;
tdata->data = struct_left;

// start the thread data
pthread_create (thread_a, NULL, &qwerty::start_compute_ans, tdata);

关于c++ - pthread_create C++ 中的无效转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17266591/

相关文章:

java - RUNNABLE Thread.State 但在 Object.wait()

c - 这个复杂的 C 类型声明是什么意思?

c++ - 使用 2 种方法提取容器中的数据( pop_front 和 front )

C++11 线程 : Exception when called using lambdas

C++ 在 else/if 中声明一个优先级队列?

安卓2.1 : Multiple Handlers in a Single Activity

c - 函数指针的初始值

c++ - 带函数指针的模板推导还原

c++ - 在 C++ 中使用变量的值作为下一个变量的名称

c++ - 序列化boost数组