Chinaunix首页 | 论坛 | 博客
  • 博客访问: 99452
  • 博文数量: 23
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 140
  • 用 户 组: 普通用户
  • 注册时间: 2014-04-22 10:44
文章分类

全部博文(23)

文章存档

2018年(3)

2017年(1)

2015年(1)

2014年(18)

我的朋友

分类: C/C++

2014-09-02 10:21:05

嵌入式中线程应用还是看需求,一般不常用(在不会使用的情况下)

一、编译有线程的应用程序需要编译时指定编译lib库 ( -l pthread) 如:gcc main.c -o main -l pthread 才能编译通过。

二、线程使用。
1、线程运行时有分离模式和非分离模式。
简单一点说分离模式就是,把线程和自己所在的进程中分离出去,由系统去分出时间片去执行线程,此时主进程会继续向下执行。
而非分离模式是等待线程执行完毕后,进程会继续向下执行。
而在创建线程后系统默认的都是非分离模式的,so 需要设置分离模式时需要特定的设置才可以。
2、设置分离模式
方法一、通过设置线程分离模式的属性使线程分离执行(实时性好)


  1. void process_printf()
  2. {
  3.     sleep(1);
  4.     printf("sleep in thread\n");
  5. }

  6. int main()
  7. {
  8.     pthread_t thread_id;
  9.     int ret;
  10.     pthread_attr_t attr;
  11.     pthread_attr_init(&attr);
  12.     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  13.     ret = pthread_create(&thread_id, &attr, process_printf, NULL) ;
  14.     pthread_attr_destroy(&attr);

  15.     return 1;
  16. }


方法二、设置分离属性,使线程同步(实时性好)

  1. void process_printf()
  2. {
  3.     //pthread_detach(()); //method 1: 可以在线程中设置分离模式
  4.     sleep(1);
  5.     printf("sleep in thread \n");
  6. }

  7. int down_or_up_to_cloud()
  8. {
  9.     pthread_t thread_id;
  10.        int ret;
  11.  
  12.     ret = pthread_create(&thread_id, NULL, process_printf, NULL) ;
  13.     pthread_detach(thread_id); //method 2: 线程创建完毕设置分离模式 
  14.     
  15.     return 1;
  16. }
好处:设置分离模式后,线程在运行完毕后,系统会回收线程中的资源,这样不会有内存泄漏的问题啦,可以放心使用。

问题:线程创建后,进程使用内存一下会增大8M以上,原因是系统创建线程后,会分配出8M 大小的线程运行缓存,但是有时候在设置分离模式后,而且确定线程已经运行完毕了,这8M内存还是没有释放,这大概是系统并未回收这个线程空间,预备下次创建线程,直接使用此线程的空间,也许就是系统的一个优化功能,此处不过多揣摩,了解一下就好。
线程的8M空间在整个进程结束后会完全释放,再次启动进程后,运行到创建线程时,此进程才会增加8M的运行空间。
3、非分离模式
当我们使用系统默认的线程处理模式时,一不小心就会导致内存泄漏的问题。
例如:

例1、非分离模式创建后,没注意回收资源,导致内存泄漏

  1. int main()
  2. {
  3.     pthread_t thread_id;
  4.     int ret;

  5.     ret = pthread_create(&thread_id, NULL, process_one, NULL) ;

  6.     ret = pthread_create(&thread_id, NULL, process_two, NULL) ;
  7.      ....
  8.     ret = pthread_create(&thread_id, NULL, process_N, NULL) ;

  9.     return 1;
  10. }
上例在主进程中创建多个线程,或者在整个应用程序中需要不定时的去创建进程去处理事情,可以确定的是每创建一个线程系统会自动开辟8M的线程缓存,这样不停的积累,内存会耗尽,导致内存泄漏。
如果一定要用非分离模式那么就需要加入回收资源的的函数。pthread_join(tid, &status);

例1、非分离模式创建后,没注意回收资源,导致内存泄漏

  1. int main()
  2. {
  3.     pthread_t thread_id_1,thread_id_2,thread_id_3...thread_id_n;
  4.     int ret;

  5.     ret = pthread_create(&thread_id_1, NULL, process_one, NULL) ;

  6.     ret = pthread_create(&thread_id_2, NULL, process_two, NULL) ;
  7.      ....
  8.     ret = pthread_create(&thread_id_n, NULL, process_N, NULL) ;
  9.      pthread_join(thread_id_1, NULL);
  10.       pthread_join(thread_id_2, NULL);
  11.       ...
  12.       pthread_join(thread_id_n, NULL);
  13.     return 1;
  14. }
添加thread_join 函数是等待线程运行完毕后,然后回收资源的作用。so 线程好用,但要慎用,别出问题都不知道在哪儿出错了。


好了,就先简单说一下吧,欢迎指出问题,共同进步!




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