1// A benchmark that executes malloc/free pairs in parallel.
2// Usage: ./a.out number_of_threads total_number_of_allocations
3// RUN: %clangxx_lsan %s -o %t
4// RUN: %env_lsan_opts=use_ld_allocations=0 %run %t 5 1000000 2>&1
5#include <assert.h>
6#include <pthread.h>
7#include <stdlib.h>
8#include <stdio.h>
9
10int num_threads;
11int total_num_alloc;
12const int kMaxNumThreads = 5000;
13pthread_t tid[kMaxNumThreads];
14
15pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
16pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
17bool go = false;
18
19void *thread_fun(void *arg) {
20 pthread_mutex_lock(mutex: &mutex);
21 while (!go) pthread_cond_wait(cond: &cond, mutex: &mutex);
22 pthread_mutex_unlock(mutex: &mutex);
23 for (int i = 0; i < total_num_alloc / num_threads; i++) {
24 void *p = malloc(size: 10);
25 __asm__ __volatile__("" : : "r"(p) : "memory");
26 free(ptr: (void *)p);
27 }
28 return 0;
29}
30
31int main(int argc, char** argv) {
32 assert(argc == 3);
33 num_threads = atoi(nptr: argv[1]);
34 assert(num_threads > 0);
35 assert(num_threads <= kMaxNumThreads);
36 total_num_alloc = atoi(nptr: argv[2]);
37 assert(total_num_alloc > 0);
38 printf(format: "%d threads, %d allocations in each\n", num_threads,
39 total_num_alloc / num_threads);
40 for (int i = 0; i < num_threads; i++)
41 pthread_create(newthread: &tid[i], attr: 0, start_routine: thread_fun, arg: 0);
42 pthread_mutex_lock(mutex: &mutex);
43 go = true;
44 pthread_cond_broadcast(cond: &cond);
45 pthread_mutex_unlock(mutex: &mutex);
46 for (int i = 0; i < num_threads; i++) pthread_join(th: tid[i], thread_return: 0);
47 return 0;
48}
49

source code of compiler-rt/test/lsan/TestCases/high_allocator_contention.cpp