循环pthread_create导致虚拟内存上涨

本文介绍了一个因pthread_create创建线程过快而导致虚拟内存持续增长的问题,并提供了解决方案:通过在创建线程后添加usleep使线程休眠一段时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

ContractedBlock.gifExpandedBlockStart.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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值