我已经用 C++ 为多线程 tcp 服务器编写了这个类 .. 并通过::编译
g++ -o server server.cpp -lpthread
但是我收到以下错误::
invalid conversion from "void*" to "void* (*)(void*)"
initializing argument 3 of "int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)"
我该怎么办??我的代码::
#include "PracticalSocket.h"
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
class MultiThreadedServer{
private:
static const int RCVBUFSIZE = 1024;
string agent_ip;
int agent_port;
public:
string startServer(unsigned short port, string agentIP, int agentPort)
{
agent_ip = agentIP;
agent_port=agentPort;
try
{
TCPServerSocket servSock(port); // Socket descriptor for server
for (;;)
{
// Create separate memory for client argument
TCPSocket *clntSock = servSock.accept();
pthread_t threadID;
if (pthread_create(&threadID, NULL, (void*) &ThreadMain,(void *) &clntSock) != 0)
{
cerr << "Unable to create thread" << endl;
exit(1);
}
}
}
catch (SocketException &e)
{
cerr << e.what() << endl;
exit(1);
}
// NOT REACHED
}
// TCP client handling function
void static HandleTCPClient(TCPSocket *sock)
{
cout << "Handling client ";
try
{
cout<<"Foreign address: "<< sock->getForeignAddress() << ":";
}
catch (SocketException &e)
{
cerr << "Unable to get foreign address" << endl;
}
try
{
cout<<"Foreign port: "<< sock->getForeignPort();
}
catch (SocketException &e)
{
cerr << "Unable to get foreign port" << endl;
}
cout << " with thread " << pthread_self() << endl;
char echoBuffer[RCVBUFSIZE];
int recvMsgSize;
while ((recvMsgSize = sock->recv(echoBuffer, RCVBUFSIZE)) > 0)
{
cout<<"echoBuffer::::"<<echoBuffer;
//sock->send(echoBuffer, recvMsgSize);
}
// Destructor closes socket
}
static void ThreadMain(void *clntSock)
{
// Guarantees that thread resources are deallocated upon return
pthread_detach(pthread_self());
// Extract socket file descriptor from argument
HandleTCPClient((TCPSocket *) clntSock);
delete (TCPSocket *) clntSock;
//return NULL;
}
};
最佳答案
你可以直接使用方法名而不用强制转换:
pthread_create(&threadID, NULL, ThreadMain,(void *) &clntSock)
此外,该方法需要返回 void*
而不是 void
:
static void* ThreadMain(void *clntSock)
关于c++ - c++中tcp服务器中的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8821758/