dom*_*lao 1 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 *ptr )
{
/* do something here */
pthread_exit( NULL );
}
void *fthread2( void *ptr )
{
/* do something here */
pthread_exit( NULL );
}
Run Code Online (Sandbox Code Playgroud)
我的问题是当我循环pthread_create再次创建两个线程时,我的应用程序内存使用量变得越来越大.
while( 1 )
{
pthread_create( &thread1, NULL, fthread1, NULL);
pthread_create( &thread2, NULL, fthread2, NULL);
}
Run Code Online (Sandbox Code Playgroud)
我在VSZ列中使用Linux ps命令行工具确定内存消耗.
看来我错过了一些使用pthreads API的部分.如何让我的应用程序不要使用太多内存.
当线程仍在运行/尚未启动时,您可能正在创建线程.这是未定义的行为.(阅读:非常糟糕)
如果您修改您的程序:
while( 1 )
{
pthread_create( &thread1, NULL, fthread1, NULL);
pthread_create( &thread2, NULL, fthread2, NULL);
pthread_join(&thread1, NULL);
pthread_join(&thread2, NULL);
}
Run Code Online (Sandbox Code Playgroud)
在开始新线程之前,您将等待线程完成.
请注意,每个线程都有自己的调用堆栈和控制结构,并将占用内存.最好限制应用程序中的线程数,而不是以快速方式创建和销毁线程.