Im designing a multi cleint web server using multithreads in C using Pthreads, i have a Masterthread that is in a loop doing the listening, when there is a connection it spawns a new thread doing a function to serve, while the Masterthread continue listening for connection.
as i have notice from debuging, its serving only one connection at a time, the Accept() system call is waiting for that connection to close, then it will spawn the next connection in the queue.
Its acting like if its a single-thread web server.
void *ServeThread(void *param)
{ int tsk;
tsk = (int)param;
/* here im serving the connection (tsk), and then close it */
}
void *MakeThreadPool(void *param)
{
for(;;) {
length = sizeof(cli_addr);
if((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, &length)) < 0) {
exit(1);
}
temps=socketfd;
rc = pthread_create(&Thread[i++],NULL,ServeThread,(void *)temps);
}
}
How can i make accpet() contine listening al spawning theads when ever there is a connection without waiting for the previous one to finish ?
You observation is not correct,
accept(2)does not wait for established TCP connection to complete. What you see is probably thread dispatch artifact – the main thread is preempted by the newly spawned thread and does not get to run until that one completes.In general, thread-per-connection is a workable strategy, but you might want to create a pool of threads before accepting connection, instead of starting a new one every time.