I am writing a simple multi-client server communication program using POSIX threads in C. I am creating a thread every time a new client is connected, i.e. after the accept(...)
routine in main()
.
I have put the accept(...)
and the pthread_create(...)
inside a while(1)
loop, so that server continues to accept clients forever. Now, where should I write the pthread_join(...)
routine after a thread exits.
More Info: Inside the thread's "start routine", I have used poll()
& then recv()
functions, again inside a while(1)
loop to continuously poll for availability of client and receive the data from client, respectively. The thread exits in following cases:
1) Either poll()
returns some error event or client hangs up.
2) recv()
returns a value <= 0.
Language: C
Platform: Suse Linux Enterprise Server 10.3 (x86_64)
First up starting a new thread for each client is probably wasteful and surely won't scale very far. You should try a design where a thread handles more than one client (i.e. calls poll
on more than one socket). Indeed, that's what poll(2)
, epoll
etc were designed for.
That being said, in this design you likely needn't join the threads at all. You're not mentioning any reason why the main thread would need information from a thread that finished. Put another way, there's no need for joining.
Just set them as "detached" (pthread_detach
or pthread_attr_setdetachstate
) and they will be cleaned up automatically when their function returns.