Subj : Re: killing thread To : comp.programming.threads From : Joe Seigh Date : Wed Aug 10 2005 12:34 pm Vitale Ferruccio wrote: > Hi, > > my program runs under *nix and windows, I'm using POSIX threads. > For clearance, I report two small peace of code: > > void * > thread_timer(void *parg) > { > sleep(200); > pthread_exit(NULL); > return NULL; > } > > void * > thread_execute(void *parg) > { > pthread_cancel(thread_id_of_timer_thread); > pthread_exit(NULL); > } > > After thread_execute calls pthread_cancel, I thought that the thread > would be > cancelled: instead thread_timer exists only when 200 seconds are passed. > I could now rewrite my question: how can I put to sleep a thread and > interrupt > its execution? :-) > Assuming you have a signal handler and you're using the signal to interrupt a syscall, you may have a race condition. How do you know the thread in question is in sleep()? You don't. If the signal occurred before the sleep then what you're seeing is allowable. Use pthread_cond_signal and pthread_cond_timedwait with a "signaled" flag. ts.tv_sec = time() + 200; ts.tv_nsec = 0; pthread_mutex_lock(&mutex); while (!signaled) pthread_cond_timedwait(&cvar, &mutex, &ts); pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); signaled = 1; pthread_cond_signal(&cvar); pthread_mutex_unlock(&mutex); -- Joe Seigh When you get lemons, you make lemonade. When you get hardware, you make software. .