My main function code is shown below
if (argc < 2 || argc > 4)
{
printf("usage: server <port> [<ip>]\n");
exit(1);
}
TCPStream* stream = NULL;
TCPAcceptor* acceptor = NULL;
if (argc == 3)
{
acceptor = new TCPAcceptor(atoi(argv[1]), argv[2]);
}
else
{
acceptor = new TCPAcceptor(atoi(argv[1]));
}
if (acceptor->start() == 0)
{
while (1)
{
stream = acceptor->accept();
if (stream != NULL)
{
/*
ssize_t len;
char line[256];
while ((len = stream->receive(line, sizeof(line))) > 0) {
line[len] = 0;
printf("received - %s\n", line);
stream->send(line, len);
*/
cout << "in main" << stream->getsockdescriptor() << endl;
pthread_t sniffer_thread;
if( pthread_create( &sniffer_thread, NULL, connection_handler, (void*)&stream) < 0)
{
perror("could not create thread");
return 1;
}
//Now join the thread , so that we dont terminate before the thread
pthread_join( sniffer_thread , NULL);
}
delete stream;
}
}
exit(0);
}
and thread function code is shown below
void *connection_handler(void * args)
{
TCPStream *stream = (TCPStream *)args;
ssize_t len;
char line[256];
cout << "check1" << endl;
cout << stream->getsockdescriptor() << endl;
while ((len = stream->receive(line, sizeof(line))) > 0)
{
cout << "check2" << endl;
line[len] = 0;
printf("received - %s\n", line);
stream->send(line, len);
}
}
Even though I passed object to thread function. I am getting different file descriptor value. In main it is showing correct.Start(),Accept(),receive() are wrapper function
The problem is the pthread_create
call and the arguments you pass there:
pthread_create( &sniffer_thread, NULL, connection_handler, (void*)&stream)
Here you don't pass a pointer to a TCPStream
object (ie TCPStream*
), but a pointer to a pointer to a TCPStream
object (ie TCPSTream**
).
This will lead to undefined behavior in your thread function because you treat the pointer as a pointer to TCPStream
.
Simply drop the address-of operator &
when calling pthread_create
and it should start working.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.