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

 

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值