Android NDK中的pthread_cancel()备选方案?

Chu*_*Fry 20 c++ pthreads android-ndk

我正在将一个中等大小的C++代码移植到Android NDK.不幸的是,pthreads实现(无论如何,NDK v5)都是不完整的.具体来说,我们的应用程序依赖于pthread_cancel()来终止工作线程.NDK没有实现pthread_cancel()!当工作线程正常响应时,还有其他明显的答案.但是在工作线程没有响应的情况下(例如无限循环),如何在不杀死整个过程的情况下取消它?

Rya*_*sen 16

适用于这个人的可能选项:http://igourd.blogspot.com/2009/05/work-around-on-pthreadcancel-for.html

在此重新发布:

然后我使用pthread_kill触发SIG_USR1信号并使用信号处理程序退出此pthread并尝试它,它可以工作,但仍然想知道这种方法是否有任何缺点.

定时器输出:

if ( (status = pthread_kill(pthread_id, SIGUSR1)) != 0) 
{ 
    printf("Error cancelling thread %d, error = %d (%s)", pthread_id, status, strerror status));
} 
Run Code Online (Sandbox Code Playgroud)

USR1处理程序:

struct sigaction actions;
memset(&actions, 0, sizeof(actions)); 
sigemptyset(&actions.sa_mask);
actions.sa_flags = 0; 
actions.sa_handler = thread_exit_handler;
rc = sigaction(SIGUSR1,&actions,NULL);
void thread_exit_handler(int sig)
{ 
    printf("this signal is %d \n", sig);
    pthread_exit(0);
}
Run Code Online (Sandbox Code Playgroud)

看起来最好的答案是重写,以便线程不等待IO:http://groups.google.com/group/android-platform/browse_thread/thread/0aad393da2da65b1

  • 是的,这是一个耻辱,不在当前的Android NDK,添加一些恼人的任务.多平台开发的乐趣.我们很容易移植我们的线程库,因为我们不必使用pthread_cancel或信号量,但看起来某种重写/接口实现必须由于丢失而改变. (2认同)
  • 设计 pthread_cancel() 时考虑了取消信号。pthread_cancel() 的手册页描述了他们选择背后的理由:“考虑了两个替代函数来向线程发送取消通知。一个是定义一个新的 SIGCANCEL 信号,该信号在传递时具有取消语义;另一个是定义新的 pthread_cancel() 函数,它将触发取消语义。” 有关他们为何选择的更多详细信息,请参阅手册页。 (2认同)