Recently, I'm learning about multithreading. There is some confusion about the memory usage of multiple threads. Does multi-threaded code increase real-time memory usage? I wrote the following two pieces of code. First, single-thread implementation of code is as follows:
for (int i = 0; i < 1000; i )
{
A* pA = new A;
pA->dosomething();
delete pA;
}
First, multi-thread implementation of code is as follows:
#pragma omp parallel for
for (int i = 0; i < 1000; i )
{
A* pA = new A;
pA->dosomething();
delete pA;
}
Is it possible that the multi-thread code occupies 1000 A-size memory at a certain time?But single-threaded program occupies a maximum of one A memory at a certain time. I'm not sure if my understanding is correct. Can someone help me with that? Thank you.
CodePudding user response:
I test the code for single thread and multiread. And the result shows the multi-threaded code increase real-time memory usage. And the amount of memory added depends on how much memory is being consumed simultaneously in multiple threads.
For example, single-thread implementation of code is as follows:
#include <omp.h> // OpenMP
#include<stdlib.h>
#include <memory.h>
#include<stdio.h>
using namespace std;
void* create(unsigned int size)
{
void *m = malloc(size);
memset(m,0,size);
return m;
}
void create_destory(unsigned int size)
{
void* p = create(size);
free(p);
}
int main()
{
unsigned int mega = 1024 * 1024 * 1024;
for (int i = 0; i < 4; i )
{
create_destory(mega);
}
}
The compilation options are as follows:
g test_memory_single_thread.cc -fopenmp -std=c 11 -o test_memory_single_thread
Then use /usr/bin/time -v to test the peak memory usage of a process
/usr/bin/time -v ./test_memory_single_thread
The result shows the Maximum resident set size(kbytes) is 1049928 I tested it many times. The Maximum resident set size(kbytes) is always about 1049928
Secondly, multi-thread implementation of code is as follows:
#include <omp.h> // OpenMP
#include <memory.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
void* create(unsigned int size)
{
void *m = malloc(size);
memset(m,0,size);
return m;
}
void create_destory(unsigned int size)
{
void* p = create(size);
free(p);
}
int main()
{
unsigned int mega = 1024 * 1024 * 1024;
#pragma omp parallel for
for (int i = 0; i < 4; i )
{
create_destory(mega);
}
}
The compilation options are as follows:
g test_memory_multi_thread.cc -fopenmp -std=c 11 -o test_memory_multi_thread
Then use /usr/bin/time -v to test the peak memory usage of a process
/usr/bin/time -v ./test_memory_multi_thread
The result shows the Maximum resident set size(kbytes) is 3037564
I tested it many times. The Maximum resident set size(kbytes) may be 3627164, 2925496 and so on
Therefore, the result shows the multi-threaded code increase more real-time memory usage.