pthread_cancel() 并使用清理处理程序。
pthread_cancel() and using cleanup handlers.
我在取消 pthread 和使用清理处理程序时遇到问题。
在 POSIX 库中有两个函数:
pthread_cleanup_push 和 pthread_cleanup_pop。
问题是它们不是函数,而是 宏!
此外,它们似乎必须 成对 放置,即对于每次推送,也必须有弹出。但我觉得有点奇怪。
假设我有这样的代码结构:
{
pthread_mutex_lock(&mutex);
pthread_cleanup_push(cleanup_mutex, &mutex);
// any code that can be cancellation point
while(/*some condition *) {
// any code that cancellation point
// 1. signaled -> thread given mutex
// 2. timeout -> thread given mutex
// 3. canceled -> thread given mutex and than cleanup handlers
if(pthread_cond_timedwait(&cond, &mutex, &abstimeout) == ETIMEDOUT) {
/*** HERE SHOULD BE pthread_cleanup_pop(0)! But it cannot be placed! case 2)***/
pthread_mutex_unlock(&mutex);
return NULL;
}
}
// any code that can be cancellation point
// consume something
// any code that can be cancellation point
pthread_cleanup_pop(0); // takes care of case 1)
pthread_mutex_unlock(&mutex);
return something;
}
是的,有点奇怪,但事实就是如此。最坏的情况下,您可以使用 goto
跳转到适当范围内的 return
语句。但通常有一种更自然的方式来做到这一点。
我在取消 pthread 和使用清理处理程序时遇到问题。 在 POSIX 库中有两个函数: pthread_cleanup_push 和 pthread_cleanup_pop。 问题是它们不是函数,而是 宏! 此外,它们似乎必须 成对 放置,即对于每次推送,也必须有弹出。但我觉得有点奇怪。
假设我有这样的代码结构:
{
pthread_mutex_lock(&mutex);
pthread_cleanup_push(cleanup_mutex, &mutex);
// any code that can be cancellation point
while(/*some condition *) {
// any code that cancellation point
// 1. signaled -> thread given mutex
// 2. timeout -> thread given mutex
// 3. canceled -> thread given mutex and than cleanup handlers
if(pthread_cond_timedwait(&cond, &mutex, &abstimeout) == ETIMEDOUT) {
/*** HERE SHOULD BE pthread_cleanup_pop(0)! But it cannot be placed! case 2)***/
pthread_mutex_unlock(&mutex);
return NULL;
}
}
// any code that can be cancellation point
// consume something
// any code that can be cancellation point
pthread_cleanup_pop(0); // takes care of case 1)
pthread_mutex_unlock(&mutex);
return something;
}
是的,有点奇怪,但事实就是如此。最坏的情况下,您可以使用 goto
跳转到适当范围内的 return
语句。但通常有一种更自然的方式来做到这一点。