Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_cancel() alternatives in Android NDK?

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?

like image 735
Chuck Fry Avatar asked Jan 05 '11 23:01

Chuck Fry


1 Answers

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

like image 135
Ryan Christensen Avatar answered Nov 08 '22 22:11

Ryan Christensen