嵌入式中线程应用还是看需求,一般不常用(在不会使用的情况下)
一、编译有线程的应用程序需要编译时指定编译lib库 ( -l pthread) 如:gcc main.c -o main -l pthread 才能编译通过。
二、线程使用。
1、线程运行时有分离模式和非分离模式。
简单一点说分离模式就是,把线程和自己所在的进程中分离出去,由系统去分出时间片去执行线程,此时主进程会继续向下执行。
而非分离模式是等待线程执行完毕后,进程会继续向下执行。
而在创建线程后系统默认的都是非分离模式的,so 需要设置分离模式时需要特定的设置才可以。
2、设置分离模式
方法一、通过设置线程分离模式的属性使线程分离执行(实时性好)
- void process_printf()
- {
- sleep(1);
- printf("sleep in thread\n");
- }
-
- int main()
- {
- pthread_t thread_id;
- int ret;
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
- ret = pthread_create(&thread_id, &attr, process_printf, NULL) ;
- pthread_attr_destroy(&attr);
-
- return 1;
- }
方法二、设置分离属性,使线程同步(实时性好)
- void process_printf()
- {
- //pthread_detach(pthread_self()); //method 1: 可以在线程中设置分离模式
- sleep(1);
- printf("sleep in thread \n");
- }
-
- int down_or_up_to_cloud()
- {
- pthread_t thread_id;
- int ret;
- ret = pthread_create(&thread_id, NULL, process_printf, NULL) ;
- pthread_detach(thread_id); //method 2: 线程创建完毕设置分离模式
- return 1;
- }
问题:线程创建后,进程使用内存一下会增大8M以上,原因是系统创建线程后,会分配出8M 大小的线程运行缓存,但是有时候在设置分离模式后,而且确定线程已经运行完毕了,这8M内存还是没有释放,这大概是系统并未回收这个线程空间,预备下次创建线程,直接使用此线程的空间,也许就是系统的一个优化功能,此处不过多揣摩,了解一下就好。
线程的8M空间在整个进程结束后会完全释放,再次启动进程后,运行到创建线程时,此进程才会增加8M的运行空间。
3、非分离模式
当我们使用系统默认的线程处理模式时,一不小心就会导致内存泄漏的问题。
例如:
例1、非分离模式创建后,没注意回收资源,导致内存泄漏
- int main()
- {
- pthread_t thread_id;
- int ret;
-
- ret = pthread_create(&thread_id, NULL, process_one, NULL) ;
-
- ret = pthread_create(&thread_id, NULL, process_two, NULL) ;
- ....
- ret = pthread_create(&thread_id, NULL, process_N, NULL) ;
-
- return 1;
- }
如果一定要用非分离模式那么就需要加入回收资源的的函数。pthread_join(tid, &status);
例1、非分离模式创建后,没注意回收资源,导致内存泄漏
- int main()
- {
- pthread_t thread_id_1,thread_id_2,thread_id_3...thread_id_n;
- int ret;
-
- ret = pthread_create(&thread_id_1, NULL, process_one, NULL) ;
-
- ret = pthread_create(&thread_id_2, NULL, process_two, NULL) ;
- ....
- ret = pthread_create(&thread_id_n, NULL, process_N, NULL) ;
- pthread_join(thread_id_1, NULL);
- pthread_join(thread_id_2, NULL);
- ...
- pthread_join(thread_id_n, NULL);
- return 1;
- }
好了,就先简单说一下吧,欢迎指出问题,共同进步!