I have a strange problem with pthread_cond_timedwait (): according to the POSIX specification, this is a cancellation point. However, when I call pthread_cancel () on the thread, it never cancels! Instead, pthread_cond_timedwait () continues to work normally. It does not block or nothing, it just works as if pthread_cancel () was never called. However, as soon as I insert the pthread_testcancel () call, the thread is canceled correctly! Without calling pthread_testcancel (), the thread is never canceled, although I always call pthread_cond_timedwait ().
Does anyone have any idea what is going wrong here? Many thanks!
EDIT: Here is the code:
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
static int clock_gettime(int clk_id, struct timespec* t)
{
struct timeval now;
int rv = gettimeofday(&now, NULL);
if(rv) return rv;
t->tv_sec = now.tv_sec;
t->tv_nsec = now.tv_usec * 1000;
return 0;
}
static void *threadproc(void *data)
{
pthread_mutex_t mutex;
pthread_mutexattr_t attr;
pthread_cond_t cond;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex, &attr);
pthread_mutexattr_destroy(&attr);
pthread_cond_init(&cond, NULL);
for(;;) {
struct timespec ts;
clock_gettime(0, &ts);
ts.tv_nsec += 60 * 1000000;
pthread_mutex_lock(&mutex);
pthread_cond_timedwait(&cond, &mutex, &ts);
pthread_mutex_unlock(&mutex);
#if 0
pthread_testcancel();
#endif
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t pThread;
pthread_create(&pThread, NULL, threadproc, NULL);
printf("Waiting...\n");
sleep(5);
printf("Killing thread...\n");
pthread_cancel(pThread);
pthread_join(pThread, NULL);
printf("Ok!\n");
return 0;
}
source
share