C++ Android NDK 中的 pthread_cancel() 替代方案?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4610086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:55:24  来源:igfitidea点击:

pthread_cancel() alternatives in Android NDK?

c++pthreadsandroid-ndk

提问by Chuck Fry

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?

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

采纳答案by Ryan Christensen

Possible option that works for this guy: http://igourd.blogspot.com/2009/05/work-around-on-pthreadcancel-for.html

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

Reposting here in case:

在这里重新发布以防万一:

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.

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

Timer out:

超时:

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

USR1 handler:

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);
}

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

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

回答by tux_mind

I made a small library that take care of this.

我做了一个小型图书馆来处理这个问题。

It exploits some unused bits of the bionic thread structure.

它利用了仿生线程结构的一些未使用的位。

I called it libbthread:)

我称之为libbthread:)

Enjoy ;)

享受 ;)