代码之家  ›  专栏  ›  技术社区  ›  domlao

使用pthread,我的app mem使用量正在增长

  •  1
  • domlao  · 技术社区  · 16 年前

    int main()
    {
       pthread_t thread1, thread2;
       pthread_create( &thread1, NULL, fthread1, NULL );
       pthread_create( &thread2, NULL, fthread2, NULL );
    
       return 0;
    }
    
    void *fthread1( void *ptr )
    {
       /* do something here */
       pthread_exit( NULL );
    }
    
    void *fthread2( void *ptr )
    {
       /* do something here */  
       pthread_exit( NULL );
    }
    

    while( 1 )
    {
       pthread_create( &thread1, NULL, fthread1, NULL);
       pthread_create( &thread2, NULL, fthread2, NULL);
    }
    

    我使用linuxps命令行工具在VSZ列中确定内存使用量。

    3 回复  |  直到 16 年前
        1
  •  5
  •   Yann Ramin    16 年前

    当线程仍在运行/尚未启动时,您可能正在创建线程。这是未定义的行为(阅读:非常糟糕)

    while( 1 )
    {
       pthread_create( &thread1, NULL, fthread1, NULL);
       pthread_create( &thread2, NULL, fthread2, NULL);
       pthread_join(&thread1, NULL);
       pthread_join(&thread2, NULL);
    }
    

    在启动新线程之前,您将等待线程完成。

    请注意,每个线程都有自己的调用堆栈和控制结构,并且会消耗内存。最好限制应用程序中的线程数,不要快速创建和销毁线程。

        2
  •  4
  •   Tim Schaeffer    16 年前

    在循环创建新线程之前,请确保当前线程已完成:

    while( 1 )
    {
       pthread_create( &thread1, NULL, fthread1, NULL);
       pthread_create( &thread2, NULL, fthread2, NULL);
       pthread_join(&thread1);
       pthread_join(&thread2);
    }
    

        3
  •  0
  •   David Schwartz    15 年前

    每个线程都必须分离或连接。你不分离你的线程,你不创建它们分离,你不加入它们。pthreads实现必须永远保持线程,因为它无法知道您从未打算加入它们。