Linux下多线程程序消耗虚拟内存测试
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <string.h>
#include <fcntl.h> 
#include <unistd.h>  
#include <time.h>
#include <stdlib.h>
#include <pthread.h> 

int new_size = 1 * 1024 * 1024;
int g_write_flg = 0;

void run_cpu()
{
	int a = 1;
	for (int i = 1; i < 1000 * 1000 * 1000; ++i)
	{
		a = a/i;
	}
}

void writefile(FILE* f,char *fname,char * ctx,int nsize)
{
	f = fopen(fname, "w");//
	if (f)
	{
		fwrite(ctx, 1, nsize, f);
		fclose(f);
	}
	else
	{
		printf("writefile fopen failed!\n");
	}
}

void* test_fun(void* fd)
{
	printf("test_fun begin.... idx:%d\n", *(int*)fd);
	sleep(10);
	if (new_size > 0)
	{
		printf("nnnnn\n");
		char* p = new char[new_size];
		sleep(10);
		printf("ddddd\n");
		delete[] p;
		sleep(10);
		printf("n2n2n2n2\n");
		p = (char*)malloc(new_size);
		sleep(10);
		printf("d2d2d2\n");
		free(p);
	}
	printf("over sleep...\n");
	sleep(10);
	printf("over !\n");
	
	/*
	int idx = *(int*)fd;
	char cfile[10];
	sprintf(cfile, "./out%d.txt", idx);
	FILE* f = NULL;// fopen(cfile, "w");
	while (true)
	{
		char* p = new char[new_size];
		//memset(p, idx, new_size);
		if (g_write_flg)
		{
			printf("write file :%s size:%d MB\n",cfile, new_size/(1024*1024));
			writefile(f,cfile, p, new_size);
		}
		//run_cpu();
		delete[] p;
		sleep(10);
	}*/

	pthread_exit(NULL);
}

void create_test_thread(int idx, pthread_t &thread)
{
	int *tmpidx = new int;
	*tmpidx = idx;
	if (pthread_create(&thread, NULL, test_fun, tmpidx) != 0)//创建子线程  
	{
		perror("pthread_create check_inite_rknn_stuck");
	}
	/*else {
		pthread_detach(thread);
	}*/
}

int main(int argc, char *argv[])
{//参数1:是否写文件  参数2:测试线程个数 参数3:每次申请内存大小(M)
	if (argc != 4)
	{
		printf("input arg param is error! \n");
		return 0;
	}
	g_write_flg = atoi(argv[1]);
	int threadnum = atoi(argv[2]);
	int nsize = atoi(argv[3]);
	new_size = nsize * new_size;
	printf("write_flg:%d thread num:%d new_size:%d\n",g_write_flg,threadnum, nsize);
	pthread_t thread[1024];
	for (int i = 0; i < threadnum; ++i)
	{
		create_test_thread(i,thread[i]);
		sleep(1);
	}

	for (int i = 0; i < threadnum; ++i)
	{
		printf("exit thread:%d ret:%d",i,pthread_join(thread[i],NULL));
	}

	while (true)
	{
		printf("test running ...\n");
		sleep(20);
	}

	return 0;
}

  进程创建了一个线程并且在该线程内分配一个很小的内存1k,整个进程虚拟内存立马增加64M,然后再分配,内存就不增加了。

如果申请较大内存如1M则不会从64M空间中申请,只有小内存才会。

https://zhuanlan.zhihu.com/p/492114502

posted on 2022-06-15 11:11  DuoRuaiMi4567  阅读(100)  评论(0编辑  收藏  举报