Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1214385
  • 博文数量: 261
  • 博客积分: 4196
  • 博客等级: 上校
  • 技术积分: 3410
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-17 17:05
文章分类

全部博文(261)

文章存档

2018年(1)

2017年(22)

2016年(2)

2015年(8)

2014年(27)

2013年(40)

2012年(161)

分类: LINUX

2017-11-14 15:13:29

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);
代码

  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include<stdlib.h>
  4. #include <unistd.h>
  5. void *threadfunc(void *parm)
  6. {
  7.   printf("Entered secondary thread\n");
  8.   while (1) {
  9.     printf("Secondary thread is looping\n");
  10. //    pthread_testcancel();
  11.     sleep(1);
  12.   }
  13.   return NULL;
  14. }

  15. int main(int argc, char **argv)
  16. {
  17.   pthread_t thread;
  18.   int rc=0;

  19.   printf("Entering testcase\n");

  20.   /* Create a thread using default attributes */
  21.   printf("Create thread using the NULL attributes\n");
  22.   rc = pthread_create(&thread, NULL, threadfunc, NULL);
  23.   checkResults("pthread_create(NULL)\n", rc);

  24.   /* sleep() is not a very robust way to wait for the thread */
  25.   sleep(1);

  26.   printf("Cancel the thread\n");
  27.   rc = pthread_cancel(thread);
  28.   checkResults("pthread_cancel()\n", rc);

  29.   /* sleep() is not a very robust way to wait for the thread */
  30.   sleep(10);
  31.   printf("Main completed\n");
  32.   return 0;
  33. }


阅读(1119) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~