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

C 使用pthread,我的app mem使用量正在增长,c,linux,multithreading,pthreads,C,Linux,Multithreading,Pthreads,我使用C语言和Linux作为我的编程平台 在我的用户空间应用程序中。我使用pthread创建了一个线程 int main() { pthread_t thread1, thread2; pthread_create( &thread1, NULL, fthread1, NULL ); pthread_create( &thread2, NULL, fthread2, NULL ); return 0; } void *fthread1( void *p

我使用C语言和Linux作为我的编程平台

在我的用户空间应用程序中。我使用pthread创建了一个线程

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 );
}
我的问题是,当我循环pthread_create以再次创建两个线程时,我的应用程序内存使用量越来越大

while( 1 )
{
   pthread_create( &thread1, NULL, fthread1, NULL);
   pthread_create( &thread2, NULL, fthread2, NULL);
}
我在VSZ列中使用Linux ps命令行工具确定内存使用情况


似乎我在使用pthreadsapi时遗漏了一些内容。如何使我的应用程序不占用太多内存。

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

如果修改程序以执行以下操作:

while( 1 )
{
   pthread_create( &thread1, NULL, fthread1, NULL);
   pthread_create( &thread2, NULL, fthread2, NULL);
   pthread_join(&thread1, NULL);
   pthread_join(&thread2, NULL);
}
在启动新线程之前,您将等待线程完成


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

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

如果修改程序以执行以下操作:

while( 1 )
{
   pthread_create( &thread1, NULL, fthread1, NULL);
   pthread_create( &thread2, NULL, fthread2, NULL);
   pthread_join(&thread1, NULL);
   pthread_join(&thread2, NULL);
}
在启动新线程之前,您将等待线程完成


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

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

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

您创建线程的速度快于处理器清理线程的速度。

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

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

创建线程的速度快于处理器清理线程的速度。

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

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

您正在启动线程,每个线程都有自己的堆栈。为什么不期望内存使用量增长?但是如果线程已经完成(pthread_exit),该怎么办呢。如果不知道你在做什么以及为什么,很难知道正确的答案是什么。当然
而(1)pthread\u create
不是您的最佳选择:发布的答案提供了一个可能的解决方案。您正在启动线程,每个线程都有自己的堆栈。为什么不期望内存使用量增长?但是如果线程已经完成(pthread_exit),该怎么办呢。如果不知道你在做什么以及为什么,很难知道正确的答案是什么。当然
而(1)pthread\u create
不是您的最佳选择:贴出的答案提供了一个可能的解决方案。我们的两项发明在一个地方跳跃并相遇!(参见《驯悍记》)。我们的两项发明在一次跳跃中相遇!(参见驯服悍妇)。