我是线程的新手,这个编译错误是什么意思? [英] I am new to threads, What does this compile error mean?

查看:98
本文介绍了我是线程的新手,这个编译错误是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C ++。

pthread_t threads[STORAGE]; // 0-99

...

void run()

Error>>>    int status = pthread_create(&threads[0], NULL, updateMessages, (void *) NULL);
if (status != 0)
{
	printf("pthread_create returned error code %d\n", status);
	exit(-1);
}

...

void ClientHandler::updateMessages(void *)
{
    string reqUpdate = "91"; // Request for update
    string recvMSG;
    while (true)
    {
    	sleep(5);
    	sending(sock,reqUpdate); // send
    	recvMSG = receiving(sock); // receive
    	QString output(recvMSG);
    	emit signal_chat(output, 0);	// Print message to text box
    }
}

...

编译错误:
TCPClient.cpp:109:错误:类型为void(ClientHandler ::)(void *)不匹配'void *(*)(void *)'

我不知道什么错了。
提前感谢。

I can't figure out whats wrong. Thanks in advance.

推荐答案

指向成员函数的指针与具有相同签名的全局函数不同成员函数需要其操作的附加对象。因此,这两种类型的函数的指针是不兼容的。

A pointer to a member function is different from a global function with the same signature since the member function needs an additional object on which it operates. Therefore pointers to these two types of functions are not compatible.

在这种情况下,这意味着你不能传递一个成员函数指针到 pthread_create ,但只有指向非成员(或静态)函数的指针。解决这个问题的一个方法是使用 pthread_create 的第四个参数将指向一个对象的指针传递给一个全局函数,然后调用传递的对象的方法:

In this case this means that you cannot pass a member function pointer to pthread_create but only a pointer to a non-member (or static) function. A work around for this problem is to use the forth parameter of pthread_create to pass a pointer to a object to a global function which then calls the method of the passed object:

class ClientHandler {
public:
   void updateMessages();
   void run();
};

// Global function that will be the threads main function.
// It expects a pointer to a ClientHandler object.
extern "C"
void *CH_updateMessages(void *ch) {
   // Call "real" main function
   reinterpret_cast<ClientHandler*>(ch)->updateMessages();
   return 0;
}

void ClientHandler::run() {
  // Start thread and pass pointer to the current object
  int status = pthread_create(&threads[0], NULL, CH_updateMessages, (void*)this);
  ...
}

这篇关于我是线程的新手,这个编译错误是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆