android ndk not support pthread_cancel

本文讨论了在Android NDK中遇到的pthread_cancel不支持问题及其潜在风险,如内存泄漏和死锁。建议通过改变代码,避免线程等待资源或使用信号量替代,比如pthread_kill配合特定信号,或利用开关变量让线程优雅退出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请注明:  http://blog.youkuaiyun.com/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时间片到来的时候,改变开关变量的值,让线程在释放各种资源后自动退出。

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



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值