您的位置:首页 > 其它

关于线程的删除:pthread_cancel函数的替代

2015-03-12 19:50 531 查看
很早以前有做过关于线程删除线程的调查,原本在查找文档时看到该函数,

pthread_cancel,但是该函数有一些使人厌烦的地方,就是当你当你有调

的线程已经申请完内存,还没进行free时,你将该线程给删除了,但是你

malloc的内存还是存在,这样就造成了内存泄露了,但是如何解决该问题

呢?

1)第一次想到的解决方法:调用 pthread_kill函数,pthread_kill(tid,SIGKILL)

 杀掉自己想杀掉的线程,但是调用该函数之后就将整个进程都杀掉了。

这是为什么呢?

        because pthread_kill内存封装的是 kill 函数,同时线程共享进程的资源,

当你想要杀掉线程的时候,信号是有经过进程,所以进程首先接收到该信号

将整个进程kill掉了;

 

2)那么还有其他方法可以实现呢?而且要保证资源释放掉,后面想到线程

的自身接收函数 pthread_exit ,如何使要被杀掉的线程调用该函数呢,后面

的方法也是和  1)中差不多的,就是自定义一个句柄函数 handl,然后在句柄

中 调用 pthread_exit;

以下是简单的实现代码






#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<mqueue.h>
#include<sys/syscall.h>
#include<signal.h>
#include<stdlib.h>

pthread_t pthread_id,pthread_id1;
pid_t pid;

void handle(int signal, siginfo_t *siginfo, void *u_contxt)
{
printf("\thandle exec for kill\n");
//exit(0);
pthread_exit(NULL);
return;
}

void *test_thread(void *arg)
{
sleep(3);

printf("thread tid = %d\n",syscall(SYS_gettid));
for(;;)
{
printf("phread live\n");
sleep(1);
}
}

void *test_kill(void *arg1)
{
sleep(10);
int ret = pthread_kill(pthread_id,SIGUSR2);
printf("\t\texec test_kill\n");
if(ret == 0)
{
printf("pthread_kill success\n");
}
else
{
printf("pthread_kill error\n");
}
for(;;)
{
sleep(1);
printf("test_kill pthread is live\n");
}
}

int main(int argc,char **argv)
{

/* Set SIGUSR2 */
struct sigaction sigact;
sigact.sa_sigaction = handle;
sigact.sa_flags = SA_SIGINFO;
sigemptyset(&sigact.sa_mask);
sigaction(SIGUSR2, &sigact, NULL);

pid = getpid();
printf("main process pid = %d\n",pid);

pthread_create(&pthread_id,NULL,test_thread,NULL);
pthread_create(&pthread_id1,NULL,test_kill,NULL);

for(;;);
return 0;
}


代码实现结果:

[root@localhost test_signal]# ./testSigSupend
main process pid = 5690
thread tid = 5691
phread live
phread live
phread live
phread live
phread live
phread live
phread live
handle exec for kill
exec test_kill
pthread_kill success
test_kill pthread is live
test_kill pthread is live
test_kill pthread is live
test_kill pthread is live
test_kill pthread is live
test_kill pthread is live
test_kill pthread is live
test_kill pthread is live
test_kill pthread is live
^C
[root@localhost test_signal]#


编译命令:gcc -g testSigSupend.c -o testSigSupend -lpthread

 

好了,有点累,下班下班。

生活就是: 蹋刃而行!

 

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