循环pthread_create导致虚拟内存上涨

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
     
// 测试pthread_create创建太快导致虚拟内存一直上涨直至上限
// pthread_create_test.c
#include < pthread.h >
#include
< stdio.h >
#include
< sys / wait.h >
#define WAITTIME 500000

void * Client_TS_handle_ss_local_data_cmd( void * arg)
{
printf(
" enter local ss handler\n " );

printf(
" leave local ss handler\n " );
usleep(WAITTIME);
pthread_detach(pthread_self());

pthread_exit(NULL);
}
void * Client_TS_handle_up_local_data_cmd( void * arg)
{
printf(
" enter local up handler\n " );

printf(
" leave local up handler\n " );
usleep(WAITTIME);

pthread_detach(pthread_self());

pthread_exit(NULL);
}





int main()
{
pthread_t _local_up_thread;
pthread_t _local_ss_thread;

while ( 1 )
  {
    
if (pthread_create( & _local_up_thread,NULL,Client_TS_handle_up_local_data_cmd,NULL) != 0 )

{
perror(
" Error Creating UP Thread " );
}
usleep(
1000 );
    if (pthread_create( & _local_ss_thread,NULL,Client_TS_handle_ss_local_data_cmd,NULL) != 0 )

{
perror(
" Error Creating SS Thread " );
}
}
return 0 ;
}


编译运行后查看虚拟内存上涨,导致这个原因是因为pthread_create创建线程太快,而且每个线程运行时间都教长,因此循环创建线程都需要注意这个问题,现在的解决方法是在pthread_create创建线程之后添加usleep()使其休眠一段时间,具体时间可以使用算法动态修改,也可以确定一个定值

 

转载于:https://www.cnblogs.com/eavn/archive/2010/08/29/1812040.html

你可能感兴趣的:(循环pthread_create导致虚拟内存上涨)