linux 線程函數小結

由於主線程已經開始跑了,次線程還在使用串口打印需要一點時間,因此打印的都是重複的。

#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;
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章