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

  • 相关阅读:
    WEB API 系列(二) Filter的使用以及执行顺序
    C# 各个版本特征
    dapper使用
    windows设置自动清理log
    [Mime] MimeReader--读取Mime的帮助类 (转载)
    [Mime] MimeHeaders--MimeHeader帮助类 (转载)
    [Mime] MimeEntity--MimeEntity Mime实体帮助类 (转载)
    [Mime] MediaTypes--电子邮件类型类 (转载)
    [Json] C#ConvertJson|List转成Json|对象|集合|DataSet|DataTable|DataReader转成Json (转载)
    [功能帮助类] JsHelper--Javascript操作帮助类 (转载)
  • 原文地址:https://www.cnblogs.com/jack-hzm/p/11372276.html
Copyright © 2011-2022 走看看