开发者

pthread_cancel() alternatives in Android NDK?

开发者 https://www.devze.com 2023-02-02 10:42 出处:网络
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 ki

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 doe开发者_开发问答s 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?


Possible option that works for this guy: 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.

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:

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


I made a small library that take care of this.

It exploits some unused bits of the bionic thread structure.

I called it libbthread :)

Enjoy ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号