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<stdio.h>
using namespace std;
void* create(unsigned int size)
{
return malloc(size);
}
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 1460
I tested it many times. The Maximum resident set size(kbytes) is always about 1460
Secondly, multi-thread implementation of code is as follows:
#include <omp.h> // OpenMP
#include<stdlib.h>
#include<stdio.h>
using namespace std;
void* create(unsigned int size)
{
return malloc(size);
}
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 7992
I tested it many times. The Maximum resident set size(kbytes) may be 3880, 7992, 1920 and so on
Therefore, the result shows the multi-threaded code increase more real-time memory usage.