Chinaunix首页 | 论坛 | 博客
  • 博客访问: 9368
  • 博文数量: 13
  • 博客积分: 590
  • 博客等级: 中士
  • 技术积分: 140
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-10 09:41
文章分类
文章存档

2010年(13)

我的朋友
最近访客

分类:

2010-12-06 13:21:41

phtread 的建立

#include <pthread.h>

       int pthread_create(pthread_t *restrict thread,
              const pthread_attr_t *restrict attr,
              void *(*start_routine)(void*), void *restrict arg);


错误编号:
EPERM 权限不够
EAGAIN 没有资源

pthread在建立的时候可以设置属性,属性作为一个对象存在,需要init,需要使用接口进行调用

  pthread_attr_t attr;
  /* Initialize mutex and condition variable objects */
  pthread_mutex_init(&count_mutex, NULL);
  
  /* For portability, explicitly create threads in a joinable state */
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  pthread_create(&threads[0], &attr, watch_count, (void *)t1);

这样我就创建另一个可以接join的线程,但是通常我们会创建一个detached的线程。会将属性设置为PTHREAD_CREATE_DETACHED。

还有两种灵活的detach方式:

#include <pthread.h>

       int pthread_detach(pthread_t thread);


一种是在需要被detach的子线程中直接调用,pthread_detach(pthread_self());
一种是在父线程中调用 pthread_detach(pthread_id);

另一个重要的属性是设置线程栈的大小:

   size_t stacksize;
   int rc;
   long t;
 
   pthread_attr_init(&attr);
   pthread_attr_getstacksize (&attr, &stacksize);

   stacksize = sizeof(double)*N*N+MEGEXTRA;
   
   pthread_attr_setstacksize (&attr, stacksize);


如果栈的空间太小,在局部变量很大的时候容易溢出。

pthread的退出


#include <pthread.h>

       void pthread_exit(void *value_ptr);


pthread退出时候可以携带状态值,可以被join他的线程收集。
在uclinux环境下如果exit 会退出所有的线程。

pthread的收集

#include <pthread.h>

       int pthread_join(pthread_t thread, void **value_ptr);


pthread创建后必须用join收集或者设置为detached属性,否则资源不会被回收,就发生了内存泄露

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