I have a client/server scenario. Client sends a message to server and immediately starts a thread that sleeps for 10 secs. While the main thread is waiting for any reply from server. If client gets any reply, within 10 sec, it will indicate the timer thread to terminate. The problem I am facing is that the thread don't terminate itself, everything else (communication, indication to thread) is fine. The code for this is:
server:
if (recvfrom(conn_sock, buf, buff_length, 0, (struct sockaddr*)&client_addr, &slen) == -1)
cout<<"ERROR: recvfrom()";
cout<<"\nRECEIVED:\nClient : "
<<"\nData : "<<buf;
cout<<"\n\n";
cout<<"\nEnter data to send(Type exit and press enter to exit) : ";
cin.getline(buf, sizeof(buf), '\n');
if(strcmp(buf,"exit") == 0)
exit(0);
if(sendto(conn_sock, buf, buff_length, 0, (struct sockaddr*)&client_addr, slen) == -1)
cout<<"ERROR: Problem sending data";
client:
cout<<"\nEnter data to send(Type exit and press enter to exit) :\n";
cin.getline(buf, sizeof(buf), '\n');
if(strcmp(buf,"exit") == 0)
exit(0);
if(sendto(conn_sock, buf, buff_length, 0, (struct sockaddr*)&serv_addr, addr_len) == -1)
cout<<"ERROR: Problem sending data";
pthread_t thread_id;
pthread_attr_t attr; // thread attribute
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&thread_id, &attr, thread_timer_process, NULL);
if(recvfrom(conn_sock, buf, buff_length, 0, (struct sockaddr*)&serv_addr, &slen) == -1) cout<<"ERROR: recvfrom()";
else
termin = true;
cout<<"\nRECEIVED:\nServer : "
<<"\nData : "<<buf;
cout<<"\n\n";
static variables and thread_timer_process():
static bool termin = false;
static int times = 10;
static const int INTERVAL_SEC = 1;
static void* thread_timer_process(void*)
{
int i=0;
cout<<"thread started\n";
signal(SIGINT, signal_callback_handler);
do
{
sleep(INTERVAL_SEC);
cout<<"In thread, i : "<<i<<"\n";
++i;
}
while(i<times && termin == false);
if(termin == true)
{
termin = false;
cout<<"--is exiting-\n";
}
pthread_exit(NULL);
cout<<"thread end\n";
}
Is this the right way of doing what I am trying to do?