您的位置:首页 > 其它

pthread_join with timeout

2014-05-05 18:41 1346 查看
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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: