【问题标题】:Invalid conversion in pthread_create c++ [duplicate]pthread_create c ++中的无效转换[重复]
【发布时间】:2013-06-24 00:27:25
【问题描述】:

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

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

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

错误是

无法将'qwerty::compute_ans'从类型'void* (qwerty::)(void*)'转换为类型'void* ()(void)'*

【问题讨论】:

标签: c++ multithreading function-pointers


【解决方案1】:

您不能将指向非静态成员函数的指针转换为指向函数的指针,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);

【讨论】:

  • 这是一个相当长的应用程序,如果我转换上述函数,我将不得不将所有其他函数转换为静态或创建一个对象!有解决办法吗?
  • 您不必这样做。我将使用该场景的解决方案更新我的答案。不过可能需要一些时间;)
  • 哦!等等……这是讽刺吗?!在过去的 10 分钟里,我一直在努力做出决定,最后得出的结论是!我想我应该继续走更长的路……:-(
  • 不,这不是讽刺。我只是想确保一切都是正确的、可编译的和工作的。另外,我想要一个 Twinkie
  • 我猜错了!!你是认真的。这个解决方案很震撼,你@Captain 也是如此
【解决方案2】:

你可以找到答案here

你应该使用静态函数来传递给 pthread。

class qwerty
{
public:
    void compute_ans(void)
    {
        std::cout << "Compute result!" << std::endl;
        return
    }

    static void hello_helper(void *context)
    {
        return ((qwerty *)context)->compute_answer();
    }
};
...
qwerty c;
pthread_t t;
pthread_create(&t, NULL, &qwerty::hello_helper, &c);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 2019-03-15
    • 2016-11-20
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 2013-11-26
    相关资源
    最近更新 更多