Aer*_*ate 1 c++ multithreading
使用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);
}
Run Code Online (Sandbox Code Playgroud)
...
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
}
}
Run Code Online (Sandbox Code Playgroud)
...
编译错误:
TCPClient.cpp:109: error: argument of type ‘void (ClientHandler::)(void*)’ does not match ‘void* (*)(void*)’
我无法弄清楚什么是错的.提前致谢.
指向成员函数的指针与具有相同签名的全局函数不同,因为成员函数需要其操作的附加对象.因此,指向这两种类型的函数的指针是不兼容的.
在这种情况下,这意味着您不能将成员函数指针传递给,pthread_create
而只能传递指向非成员(或静态)函数的指针.解决此问题的方法是使用第四个参数pthread_create
将指向对象的指针传递给全局函数,然后全局函数调用传递的对象的方法:
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);
...
}
Run Code Online (Sandbox Code Playgroud)
它与线程无关,这是一个普通的C++错误,你只是传递一个不兼容的函数指针类型.
函数指针与成员实例函数指针不同,即使它们的签名相同; 这是因为有一个隐含的引用*this传递.你无法避免这种情况.
归档时间: |
|
查看次数: |
499 次 |
最近记录: |