Skip to content

Commit 8919a1c

Browse files
committed
runtime: remove locks around malloc()/free() in mpmalloc.c for glibc-based systems
This is due to following statement in the glibc manual: To avoid corruption in multithreaded applications, mutexes are used internally to protect the memory-management data structures employed by these functions. In a multithreaded application in which threads simultaneously allocate and free memory, there could be contention for these mutexes. To scalably handle memory allocation in multithreaded applications, glibc creates additional memory allocation arenas if mutex contention is detected. Each arena is a large region of memory that is internally allocated by the system (using brk(2) or mmap(2)), and managed with its own mutexes. Having locks around them in the flang runtime library can ruin optimization effort when tcmalloc is preloaded to replace standard malloc()/free() implementation with the one optimized for reducing lock contention. Signed-off-by: Paul Osmialowski <pawel.osmialowski@arm.com>
1 parent fe5bda9 commit 8919a1c

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

runtime/flangrti/mpmalloc.c

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,28 @@
1717

1818
/* mp-safe wrappers for malloc, etc. */
1919

20+
#ifdef TARGET_LINUX
21+
#include <features.h>
22+
#endif
23+
2024
#include <stdlib.h>
2125
#include "llcrit.h"
26+
#ifndef __GNU_LIBRARY__
2227
MP_SEMAPHORE(static, sem);
28+
#endif
2329

2430
void *
2531
_mp_malloc(size_t n)
2632
{
2733
void *p;
2834

35+
#ifndef __GNU_LIBRARY__
2936
_mp_p(&sem);
37+
#endif
3038
p = malloc(n);
39+
#ifndef __GNU_LIBRARY__
3140
_mp_v(&sem);
41+
#endif
3242
return (p);
3343
}
3444

@@ -37,9 +47,13 @@ _mp_calloc(size_t n, size_t t)
3747
{
3848
void *p;
3949

50+
#ifndef __GNU_LIBRARY__
4051
_mp_p(&sem);
52+
#endif
4153
p = calloc(n, t);
54+
#ifndef __GNU_LIBRARY__
4255
_mp_v(&sem);
56+
#endif
4357
return (p);
4458
}
4559

@@ -48,9 +62,13 @@ _mp_realloc(void *p, size_t n)
4862
{
4963
void *q;
5064

65+
#ifndef __GNU_LIBRARY__
5166
_mp_p(&sem);
67+
#endif
5268
q = realloc(p, n);
69+
#ifndef __GNU_LIBRARY__
5370
_mp_v(&sem);
71+
#endif
5472
return (q);
5573
}
5674

@@ -59,7 +77,11 @@ _mp_free(void *p)
5977
{
6078
if (p == 0)
6179
return;
80+
#ifndef __GNU_LIBRARY__
6281
_mp_p(&sem);
82+
#endif
6383
free(p);
84+
#ifndef __GNU_LIBRARY__
6485
_mp_v(&sem);
86+
#endif
6587
}

0 commit comments

Comments
 (0)