0

I am trying to implement a multithreaded UDP server by creating thread.

The following method is used for creating thread.

pthread_create(&threadID, NULL, ThreadMain, threadArgs);

ThreadMain method is,

void *ThreadMain(void *threadArgs) {
  pthread_detach(pthread_self());
  int sock = ((struct ThreadArgs *) threadArgs)->sock;
  free(threadArgs);
  HandleUDPClient(sock);
  return (NULL);
}

In the HandleUDPClient method is like this,

void HandleUDPClient(int sock) {

   struct sockaddr_storage clntAddr; // Client address
   // Set Length of client address structure (in-out parameter)
   socklen_t clntAddrLen = sizeof(clntAddr);

   // Block until receive message from a client
   char buffer[MAXSTRINGLENGTH]; // I/O buffer

   // Size of received message
   ssize_t numBytesRcvd = recvfrom(sock, buffer, MAXSTRINGLENGTH, 0, (struct sockaddr *) &clntAddr, &clntAddrLen);
   ...
   ...

When I am creating socket and running the HandleUDPClient method it handles requests from client perfectly. But when I am trying to use thread, after entering the HandleUDPClient method it does not process the recvfrom method. Actually it does not wait for the client to receive any request. Program just terminates.

Can anybody tell me why this problem occurring and how can I resolve it?

fean
  • 546
  • 4
  • 12
  • 37
  • 1
    http://stackoverflow.com/questions/11624545/how-to-make-main-thread-wait-for-all-child-threads-finish - this should help. – user1770426 Oct 26 '13 at 16:00

1 Answers1

2

The problem is that you detach your threads, meaning that you will not have to wait for your threads to exit. Instead the main program continues its work, until it reaches its end and then exit, with no regard for the (detached) threads still running.

Either don't detach the threads, and use pthread_join to "join" the threads, or use pthread_exit from the main thread to make sure it will wait for all detached threads to finish.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621