linux 线程函数小结

mac2022-06-30  17

由于主线程已经开始跑了,次线程还在使用串口打印需要一点时间,因此打印的都是重复的。

#include "pthread.h" #include "stdio.h" #include "stdlib.h" static void * thread_function(void * arg ) { // printf("%s %d\n ",__FUNCTION__ , (int)arg ); printf("%s %d\n ",__FUNCTION__ , *(int*)arg ); while(1); return NULL; } int main(int argc, const char *argv[]) { pthread_t tid[10]; int i; for(i = 0; i<10 ; i++) { //pthread_create(&tid[i] ,NULL, thread_function ,(void *) i );传送值的方法 pthread_create(&tid[i] ,NULL, thread_function ,(void *) &i ); 传送地址的方法 } while(1) { //printf("%s\n",__FUNCTION__); //sleep(1); } return 0; }

  

 

 

 

1 查看线程的指令ps -eLf | grep thread ;

2 线程不是先创建的先执行,是根据内核来决定的先执行那个。

3 可以在创建线程的时候增加延时,让每个线程依次执行,这样子大的log就是顺序执行的。

 

  看某个进程的资源

top -p 4081 

 

 

线程回收,pthread_join ; 只调用pthread_exit 是不行的,只是退出线程,但是大小是没有变化的。

 pthread_join 是阻塞函数,因此可以将线程改为pthread_detach 改为detach属性,结束后自动释放资源的。

20s之后线程的资源变小

#include "pthread.h" #include "stdio.h" #include "stdlib.h" static void * thread_function(void * arg ) { printf("%s %d\n ",__FUNCTION__ , (int)arg ); //printf("%s %d\n ",__FUNCTION__ , *(int*)arg ); sleep(20); pthread_exit("I quit\n"); while(1); return NULL; } int main(int argc, const char *argv[]) { pthread_t tid[10]; int i; for(i = 0; i<10 ; i++) { pthread_create(&tid[i] ,NULL, thread_function ,(void *) i ); pthread_detach(tid[i]); //pthread_create(&tid[i] ,NULL, thread_function ,(void *) &i ); //sleep(1); } // pthread_join 是阻塞函数,因此可以将线程改为pthread_detach 改为detach属性, pthread_exit结束后自动释放资源的。/* int errno ; for(i = 0; i<10 ; i++) {   errno = pthread_join(tid[i] ,NULL);  if(errno == -1 )   {     perror("pthread_exit"); return -1 ;   } } */   while(1)   { //printf("%s\n",__FUNCTION__); //sleep(1);   }   return 0; }

 

 

转载于:https://www.cnblogs.com/jack-hzm/p/11372276.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)