http://www.linuxquestions.org/questions/programming-9/pthread_join-with-timeout-365304/
void * threadfunc (void *) {
while (!my_quit) {
/* do a bunch of stuff */
}
/* signal waiting threads that this thread is about to terminate */
pthread_mutex_lock(&my_mutex);
pthread_cond_broadcast(&my_cond);
pthread_mutex_unlock(&my_mutex);
return NULL;
}
void stop_the_thread (void) {
int e;
my_quit = true;
/* wait (with timeout) until thread has finished */
pthread_mutex_lock(&my_mutex);
e = pthread_cond_timedwait(&my_cond, &my_mutex, &my_timeout);
pthread_mutex_unlock(&my_mutex);
/* now join so we wait until thread has -really- finished */
if (e == ETIMEDOUT) {
printf("Timed out waiting for thread to exit :_(\n");
pthread_cancel(my_thread); /* try to forcefully stop it at a cancellation point */
} else
pthread_join(my_thread);
}
本文介绍了一种利用pthread库管理线程的方法,包括如何通过设置标志来停止线程、使用带超时的条件变量等待线程结束以及在超时情况下尝试取消线程。
1370

被折叠的 条评论
为什么被折叠?



