不提倡强制杀死线程,当我们的一个线程获取了一个锁,正在访问某个共享方法的时候,还没来得及解锁就被干掉了,那这个锁就永远不会被解掉了,于是所有依赖这个锁的其它线程可能就锁死了。
android的ndk中没有提供类似linux的pthread_cancel函数来杀死线程。
#include <jni.h>
#include <string>
#include<pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include "Logger.h"
pthread_t pid;
void handle_quit(int signo) {
LOGE("hxk>>>in qq handle sig!\n");
pthread_exit(0);
}
void *test(void *arg) {
signal(SIGTERM, handle_quit);
for (int i = 0; i < 100; i++) {
LOGE("hxk>>>in pthread test \n");
sleep(1);
}
}
void test1() {
pthread_create(&pid, NULL, test, NULL);
sleep(3);
if (pthread_kill(pid, 0) != ESRCH) {
LOGE("hxk>>>thread %d exists!\n");
pthread_kill(pid, SIGTERM);
// pthread_kill(pid, SIGQUIT);//无法杀死线程
// pthread_kill(pid, SIGKILL);//无法杀死线程
// pthread_exit(NULL);//this won't work
LOGE("hxk>>>after kill\n");
}
sleep(1);
}
可以看到当我们调用test1函数的时候,log如下:
08-15 20:05:15.681 6742-6762/com.supper.xkplayer E/xkplayer: hxk>>>in pthread test
08-15 20:05:16.681 6742-6762/com.supper.xkplayer E/xkplayer: hxk>>>in pthread test
08-15 20:05:17.682 6742-6762/com.supper.xkplayer E/xkplayer: hxk>>>in pthread test
08-15 20:05:18.681 6742-6761/com.supper.xkplayer E/xkplayer: hxk>>>thread -674265880 exists!
08-15 20:05:18.682 6742-6761/com.supper.xkplayer E/xkplayer: hxk>>>after kill
08-15 20:05:18.682 6742-6762/com.supper.xkplayer E/xkplayer: hxk>>>in qq handle sig!
从log中可以看到,循环中的log没有继续执行了,子线程已经被杀死了。
在Android NDK编程中,不建议直接杀死线程,因为这可能导致资源泄露和死锁。虽然Linux提供了pthread_cancel函数,但在NDK中并不支持。理想的实践是通过同步机制让线程安全退出。在示例中,调用test1函数后,观察到子线程成功被终止,但未详细说明具体实现方式。
152

被折叠的 条评论
为什么被折叠?



