int pthread_create( *restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg);
在linux C下使用pthread_create创建子线程时,默认线程状态为joinable,即子线程在执行完之后(即使调用pthread_exit()退出),其所占用资源不会立即释放,而是会等待主线程的pthread_join(id,NULL)之后才会释放资源。而在一些需要频繁开启线程的特殊情况下,此种机制就会成为很大隐患,因为,你在查看其占用资源状况时,会发现很恐怖的增长数据,最终程序会死掉。
这时我们想到,能不能在创建线程之后,就让其的资源释放与主线程脱离,而被直接回收呢? 这里,就要使用到pthread_detach函数,此函数很简单,只需要一个参数,即为线程id号。
形式主要有2种:
1.pthread_detach(pthread_self());让自身所在线程从主线程中独立出去。
2.pthread_detach(id);让指定线程从主线程中独立出去。
这样,就可以在一个子线程结束后,其所占用资源得到立刻回收。
这种需要,主要是在可能的服务器中,处理来自网页上的点击之类操作,因为网页往往不是一直与服务器处于连接,在需要时候才会创建新连接,而服务器则需要为这个新连接再次开辟新线程进行处理。
==========================分割线===========================================================================
在主线程中结束子线程方式: pthread_cancel(tid);
代码
-
#include <pthread.h>
-
#include <stdio.h>
-
#include<stdlib.h>
-
#include <unistd.h>
-
void *threadfunc(void *parm)
-
{
-
printf("Entered secondary thread\n");
-
while (1) {
-
printf("Secondary thread is looping\n");
-
// pthread_testcancel();
-
sleep(1);
-
}
-
return NULL;
-
}
-
-
int main(int argc, char **argv)
-
{
-
pthread_t thread;
-
int rc=0;
-
-
printf("Entering testcase\n");
-
-
/* Create a thread using default attributes */
-
printf("Create thread using the NULL attributes\n");
-
rc = pthread_create(&thread, NULL, threadfunc, NULL);
-
checkResults("pthread_create(NULL)\n", rc);
-
-
/* sleep() is not a very robust way to wait for the thread */
-
sleep(1);
-
-
printf("Cancel the thread\n");
-
rc = pthread_cancel(thread);
-
checkResults("pthread_cancel()\n", rc);
-
-
/* sleep() is not a very robust way to wait for the thread */
-
sleep(10);
-
printf("Main completed\n");
-
return 0;
-
}
阅读(1246) | 评论(0) | 转发(0) |