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