【问题标题】:pthread_create argument passing errorpthread_create 参数传递错误
【发布时间】:2013-05-31 07:17:24
【问题描述】:

尝试编写一些简单的多线程服务器程序,最近遇到了这个错误:

Server.cpp:64:64:错误:'void* (Server::)(void*)' 类型的参数不匹配 'void* (*)(无效*)

这是我的代码中的一些行:

头文件:

class Server
{
public:
void establishConnection(const char * );
...

private:
void *listening(void *);
void *acceptingConnection(void *);
pthread_attr_t attrr;
}

cpp 文件:

void Server:: establishConnection(const char *port_number )
{
...
  pthread_create(&listn, &attrr, Server::listening, (void*)socketfd);//pthread_t listn, socketfd is a socket destricptor(int)     
  pthread_join(listn, NULL);

}
void* Server::listening(void *arg)
{
  int socketfd = (int)arg;
  ...
}

通常,如果我在 cpp 文件而不是头文件中定义线程函数原型,它可以正常工作(当然没有 Server:: 定义)尝试了一些其他的东西,例如 (void*)Server::listening、listening、(void *)听,但仍然没有工作。你能启发我吗?如何将方法参数传递给监听方法?

其次,我目前正在学习c++(已经知道C),在c++程序中使用一些C方法,char*数组代替字符串,头文件是真的吗?如string.h、stdlib.h、pthread.h?

【问题讨论】:

标签: c++ multithreading pthreads


【解决方案1】:

您需要为pthread_create() 创建一个包装函数,并从那里调用您的类方法。

class Server
{
...   
private:
int sock;
};

extern "C" void * server_listening (void *arg) {
    Server *s = static_cast<Server *>(arg);
    return s->listening();
}

void Server:: establishConnection(const char *port_number )
{
...
  this->sock = socketfd;
  pthread_create(&listn, &attrr, server_listening, this);
  pthread_join(listn, NULL);
}

包装函数上的extern "C" 链接已就位,因为pthread_create() 是一个C 函数,并且需要一个具有C 链接的函数指针。如果您的系统上的 C ABI 和 C++ ABI 不相同,这一点很重要。类的静态方法只能有 C++ 链接。

【讨论】:

  • 得到这个错误:Server.cpp:23:15: error: ‘void*’ is not a pointer-to-object type
  • @nihirus:Hmpf,胖手指了答案。尝试使用s-&gt;listening(),而不是arg-&gt;listening()
  • 首先,感谢您的回答,仍然遇到同样的错误。
  • @nihirus:第 23 行,将 arg-&gt;listening() 更改为 s-&gt;listening()。您还可以将演员改回static_cast
【解决方案2】:

您可以阅读错误消息:

type ‘void* (Server::)(void*)’ does not match ‘void* (*)(void*)‘

因为Server::listeningServer的非静态成员函数,指针非静态成员函数不可能转换为指向非成员函数的指针。

你必须让你的Server::listening函数static,或者在Server类之外写一个独立的函数。

【讨论】:

猜你喜欢
  • 2022-01-01
  • 1970-01-01
  • 2023-03-31
  • 2022-01-06
  • 2014-05-28
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
  • 2014-12-18
相关资源
最近更新 更多