【问题标题】:pthread_create from non-static member functionpthread_create 从非静态成员函数
【发布时间】:2011-01-27 07:54:40
【问题描述】:

这有点类似于:pthread function from a class

但是最后被调用的函数是引用 this 指针,所以它不能是静态的。

void * Server::processRequest()
{
     std::string tmp_request, outRequest;
     tmp_request = this->readData();
     outRequest = this->parse(tmp_request);
     this->writeReply(outRequest);
}

void * LaunchMemberFunction(void * obj)
{
    return ((Server *)obj)->processRequest();
}

然后是 pthread_create

Server SServer(soc);

pthread_create(&handler[tcount], &attr, (void*)LaunchMemberFunction,(void*)&SServer);

错误:

SS_Twitter.cpp:819:错误:从 void* 到 void* 的无效转换 ()(void) SS_Twitter.cpp:819: 错误:初始化 int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)

的参数 3

【问题讨论】:

    标签: c++ pthreads


    【解决方案1】:

    您将第三个参数转换为 void* ((void*),然后出现错误,因为无法将 void* 转换为函数指针。

    如果你只使用&LaunchMemberFunction,我相信它应该可以编译。

    【讨论】:

      【解决方案2】:

      去掉 LaunchMemberFunction 前面的 (void*)。它既不必要又不正确,也是您错误的原因。该语言不会隐式地从 void * 转换为指向函数类型的指针,这是您编写的代码工作所必需的。 pthread_create 的参数已经是正确的类型,没有理由将其转换为其他类型。

      【讨论】:

        【解决方案3】:

        问题出在演员表上。您正在将函数指针转换为无法隐式转换为 (void (*)(void*) -- 这是 pthread_create 第三个参数接受的类型。

        您不需要转换参数,因为它是确切的类型,但如果必须,它会是:

        void LaunchMemberFunction( Server * ); // signature now does not match, cast required:
        
        static_cast<void (*)(void*)>(LaunchMemberFunction)
        // or with C casts:
        (void (*)(void*))LaunchMemberFunction
        

        【讨论】:

          【解决方案4】:

          在你的函数定义中我没有看到输入参数类型请使用如下

          void * Server::processRequest(void)
          {
               std::string tmp_request, outRequest;
               tmp_request = this->readData();
               outRequest = this->parse(tmp_request);
               this->writeReply(outRequest);
          }
          

          第二件事你不必像下面这样使用函数指针

          pthread_create(&handler[tcount], &attr, &LaunchMemberFunction,(void*)&SServer);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-04-14
            • 2021-12-03
            • 1970-01-01
            • 1970-01-01
            • 2011-05-31
            相关资源
            最近更新 更多