zoukankan      html  css  js  c++  java
  • linux 线程函数小结

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

    #include "pthread.h"
    #include "stdio.h"
    #include "stdlib.h"
    static void * thread_function(void * arg )
    {
     //	printf("%s %d
     ",__FUNCTION__ ,  (int)arg );
    	
     	printf("%s %d
     ",__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
    ",__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
     ",__FUNCTION__ ,  (int)arg );
        
         //printf("%s %d
     ",__FUNCTION__ ,  *(int*)arg );
        sleep(20);   
        pthread_exit("I quit
    ");
        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 ",__FUNCTION__); //sleep(1);
      }

      return 0;
    }

  • 相关阅读:
    晋IT分享成长沙龙集锦
    Spring、Hibernate 数据不能插入到数据库问题解决
    fancybox关闭弹出窗体parent.$.fancybox.close();
    关于Javakeywordsynchronized——单例模式的思考
    MySQL Study之--MySQL压力測试工具mysqlslap
    cocos2d-x 3.3 之卡牌设计 NO.4 定时器的使用(清理内存)
    【v2.x OGE教程 16】 Modifier使用相关
    [Python网络编程]浅析守护进程后台任务的设计与实现
    hdu 4778 Gems Fight!
    nginx负载均衡向后台传递參数方法(后端也是nginxserver)
  • 原文地址:https://www.cnblogs.com/jack-hzm/p/11372276.html
Copyright © 2011-2022 走看看