我正在尝试使用 pthread 清理功能来释放取消线程持有的互斥锁
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#define SHOW_TECH_CMD_MAX_EXEC_TIME 5 //in secs
pthread_mutex_t waitMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t testMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitCond = PTHREAD_COND_INITIALIZER;
void mutex_cleanup_handler(void *arg )
{
printf("cleanup n");
pthread_mutex_unlock( &testMutex );
}
void *execute_on_thread(void *arg);
void *execute_on_thread(void *arg)
{
pthread_cleanup_push(mutex_cleanup_handler, NULL);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_mutex_lock( &testMutex );
while(1)
{
printf(".");
}
pthread_mutex_lock( &waitMutex );
pthread_cond_signal( &waitCond );
pthread_mutex_unlock( &waitMutex );
pthread_cleanup_pop(1); // even with 1 behavior remains the same
return (void *) 0;
}
int main( )
{
pthread_t tid;
struct timespec ts;
int error;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 5;
pthread_create(&tid,NULL,execute_on_thread,NULL);
pthread_mutex_lock(&waitMutex);
error = pthread_cond_timedwait(&waitCond, &waitMutex,&ts);
pthread_mutex_unlock(&waitMutex);
printf("come here 1n");
if(error == ETIMEDOUT)
{
printf("come here 2n");
error = pthread_cancel(tid);
if(error != 0)
{
printf("come here 3n");
}
}
}
清理函数未被调用为自身线程被正确清除,但未调用清理函数
正如曼所说:
pthread_cleanup_pop() 函数删除了 清理处理程序的堆栈,如果执行,可以选择执行它 为非零值。
然后你必须写:
pthread_cleanup_pop(1);
请注意,您的线程函数定义不正确
编辑
使用您的代码,下面的更正有效。
if(error == ETIMEDOUT)
{
printf("come here 2n");
error = pthread_cancel(tid);
pthread_join(tid, NULL);
if(error != 0)
{
printf("come here 3n");
}
在应用程序结束之前,必须等待线程完成。在代码中,线程取消请求后,应用程序将立即结束。