I find truble in assigning different socket descriptor and thread id into the code fragment below
(its the server side of a posix sockets server - client):
Code:
//# includes
#define LIMIT 10
// these two will hold the socket descriptor and thread id for each thread
int sd_new[LIMIT];
thread_t thread_id[LIMIT];
struct thread_data {
int sd, sd_ctr, thread_ctr;
};
int main()
{
// socket initialization
//counters to store position within the arrays
int sd_ctr, thread_ctr;
//counter to access sd_new and thread_id arrays
int i;
//fill with zeros the arrays
for (i = 0; i < LIMIT; i++)
{ sd_new[i] = 0; }
for (i = 0; i < LIMIT; i++)
{ thread_id[i] = 0; }
//this struct will be the argument for the thread calling function
struct thread_data thread_args;
for(;;)
{
i = 0;
while (sd_new[i] != 0)
{ i++; }
int sd_ctr = i;
//socket accept();
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
i = 0;
while (thread_id[i] != 0)
{ i++; }
thread_ctr = i;
//thread_args initialization
thread_args.sd = sd_new[sd_ctr];
thread_args.sd_ctr = sd_ctr;
thread_args.thread_ctr = thread_ctr;
pthread_create(&thread_id[thread_ctr], &attr, thread_func, (void *)&thread_args);
pthread_attr_destroy(&attr);
pthread_detach(thread_id[thread_ctr]);
printf("sd: %d thread: %d\n", sd_ctr, thread_ctr);
}
}
void *thread_func(void *thread_args)
{
struct thread_data *my_data;
my_data = (struct thread_data *)thread_args;
int sd_thread = my_data->sd;
int sd_ctr = my_data->sd_ctr;
int thread_ctr = my_data->thread_ctr;
//do the work and
sd_new[sd_ctr] = 0;
close(sd_thread); /* Close socket */
thread_id[thread_ctr] = 0;
pthread_exit((void*) 0); /* Terminate thread */
}
The method works but it creates zombie threads in client ctrl+c termination.
An other problem is traced by the printf():
first client connects: sd_ctr = 0 thread_id = 0
second client connects: sd_ctr = 1 thread_id = 1
second client terminates
third client connnects: sd_ctr = 2 thread_id = 1
third client terminates
fourth client connects: sd_ctr = 1 thread_id = 1
why this happens with the socket descriptor?
Any suggestions?