I have a server program that spawns keepalive threads for each of newly created clients. I have implemented keepalive mechanism using clock(). If just one client is connected to the server, everything works just fine.
The problem happens when I try to connect (not exactly CONNECT, its UDP) multiple clients to the server. Just after the second client connects to the server, both clients/ one of the clients get timed out for no reason, ie. before its actually timed out.
Since there are multiple clients, I am pushing updated clock time (updated whenever server receives keepalive packet from client), to a map (one entry for each client). Also in the timer logic, I need to get updated clock time from the map each time. To debug this, I added a printf in timer logic. And alas! To my surprise everything works just fine with this printf!! I am not able to figure out why. Any help is appreciated. Thanks.
....
....
pthread_t thread_id[100];
int thread_no =0;
..
//thread listening for commands from client
while(1)
{
..
if(strcmp(cmd_cli, "1") == 0)
{
..
//this is how I spawn keepalive threads
pthread_create(&thread_id[thread_no], NULL, timer_fun, mac_addr);
thread_no++;
..
}
..
else if(strcmp(cmd_cli, "13") == 0)
{
// Kepalive received from client
if(this_client.state >= RUN)
{
//update timer
this_client.start = clock();
insert(t, mac_addr, this_client);
...
..
}
....
....
//keepalive thread handler on server
struct client_params details = lookup(t, mac);
details.start = clock();
insert(t, mac, details);
int sec=0, delay=8;
do
{
struct client_params details = lookup(t, mac);
clock_t difference = clock() - details.start;
sec = difference / CLOCKS_PER_SEC;
// following printf saves the timer
printf("sec = %d\n", sec);
}while ( sec < delay );
details.state = TIMEOUT;
insert(t, mac, details);
....
....
....