Android NDK 中的 pthread_cancel() 替代方案?
我正在将中型 C++ 代码体移植到 Android NDK.不幸的是,pthreads 实现(无论如何,从 NDK v5 开始)是不完整的.具体来说,我们的应用程序依赖 pthread_cancel() 来终止工作线程.NDK 没有实现 pthread_cancel()!当工作线程正常响应时,还有其他明显的答案.但是在工作线程没有响应的情况下(例如无限循环),我怎样才能在不杀死整个进程的情况下取消它?
I am porting a mid-sized body of C++ code to Android NDK. Unfortunately the pthreads implementation (as of NDK v5, anyway) is incomplete. Specifically, our application relies on pthread_cancel() to kill a worker thread. NDK does not implement pthread_cancel()! There are other obvious answers when the worker thread is responding normally. But in cases where the worker thread is not responding (e.g. infinite loop), how can I cancel it without killing the whole process?
推荐答案
适用于这个人的可能选项:http://igourd.blogspot.com/2009/05/work-around-on-pthreadcancel-for.html
Possible option that works for this guy: http://igourd.blogspot.com/2009/05/work-around-on-pthreadcancel-for.html
在此转发以防万一:
然后我使用 pthread_kill 来触发一个SIG_USR1 信号和使用信号处理程序退出这个 pthread 并尝试它,它有效,但仍然想知道是否有这种方法的缺点.
Then I use pthread_kill to trigger a SIG_USR1 signal and use signal handler to exit this pthread and tried it, it works, but still wondering if any drawbacks for this kind of method.
超时:
if ( (status = pthread_kill(pthread_id, SIGUSR1)) != 0)
{
printf("Error cancelling thread %d, error = %d (%s)", pthread_id, status, strerror status));
}
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
", sig);
pthread_exit(0);
}
看起来最好的答案是重写,这样线程就不会在 IO 上等待:http://groups.google.com/group/android-platform/browse_thread/thread/0aad393da2da65b1
Looks like the best answer is to rewrite so that threads aren't waiting on IO: http://groups.google.com/group/android-platform/browse_thread/thread/0aad393da2da65b1
相关文章