In the following code execute_on_thread()
will keep on printing ".",
while the main
function waits for a condition to be signaled from execute_on_thread
using pthread_cond_timedwait
. However, it is not timing out after the specified 20 second timeout, it just keeps printing ".", nothing else is happening.
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#define SHOW_TECH_CMD_MAX_EXEC_TIME 5 //in secs
pthread_mutex_t waitMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitCond = PTHREAD_COND_INITIALIZER;
void *execute_on_thread();
void *execute_on_thread()
{
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_mutex_lock( &waitMutex );
while(1)
{
printf(".");
}
pthread_cond_signal( &waitCond );
pthread_mutex_unlock( &waitMutex );
return (void *) 0;
}
int main( )
{
pthread_t tid;
struct timespec ts;
int error;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 20;
pthread_create(&tid,NULL,execute_on_thread,NULL);
pthread_mutex_lock(&waitMutex);
error = pthread_cond_timedwait(&waitCond, &waitMutex,&ts);
pthread_mutex_unlock(&waitMutex);
printf("come here 1\n");
if(error == ETIMEDOUT)
{
printf("come here 2\n");
error = pthread_cancel(tid);
if(error != 0)
{
printf("come here 3\n");
}
}
}