您的位置:首页 > 移动开发 > Android开发

android ndk not support pthread_cancel

2014-08-15 12:14 302 查看
http://blog.csdn.net/typename/article/details/7794958

转载请注明:  http://blog.csdn.net/typename/article/details/7794958

下面是google关于这个问题的说法:

Try changing your code so that your threads don't get stuck waiting
indefinitely for i/o. For example used conditional variables, select
or poll to wait for events, and be sure to create a 'stop-the-thread
event'. That's how any properly written code should be anyway

Another more rustic alternative is to either close/shutdown the file
descriptor or resource the thread is waiting on, or even use
pthread-kill to send a signal to the thread, since this sill make the
system call return with EINTR (you need to unblock the signal first
though)

In all cases, be sure to properly release resources when exiting thr
thread. 99% of the code that uses pthread_cancel I have seen leaks

memory, or even locks, in certain circumstances.

pthread_cancel可以说是一种暴力结束线程的方式,主线程或者A线程可以调用这个pthread_cancel ,kill掉其他线程。暴力意味着不优雅,若此时线程正在释放资源,释放线程锁,这时候有可能导致内存泄漏和deadlock等其他一些诡异现象。网上有人说用pthread_kill
+ 信号,我个人觉得这个还是挺好系统资源的。其实可以很简单的做到替换pthread_cancel的方法,通过开关变量来实现,当CPU时间片到来的时候,改变开关变量的值,让线程在释放各种资源后自动退出。

[cpp] view
plaincopy

static volatile bool switch_variable = true;  

void ThreadCallback(void *param)  

{      

    ...      

    while(switch_variable)   

    {  

       ...  

    }      

   elease some resource;  

}  

int main()  

{    

    ...    

    change switch_variable;    

    switch_variable = false;   

    ...     

    return 0;  

 }  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐