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 ;ui

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

3 能够在建立线程的时候增长延时,让每一个线程依次执行,这样子大的log就是顺序执行的。线程

 

  看某个进程的资源code

top -p 4081 blog

 

 

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

 pthread_join 是阻塞函数,所以能够将线程改成pthread_detach 改成detach属性,结束后自动释放资源的。资源

20s以后线程的资源变小it

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

 

相关文章
相关标签/搜索