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: %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);
21  while (!go) pthread_cond_wait(&cond, &mutex);
22  pthread_mutex_unlock(&mutex);
23  for (int i = 0; i < total_num_alloc / num_threads; i++) {
24    void *p = malloc(10);
25    __asm__ __volatile__("" : : "r"(p) : "memory");
26    free((void *)p);
27  }
28  return 0;
29}
30
31int main(int argc, char** argv) {
32  assert(argc == 3);
33  num_threads = atoi(argv[1]);
34  assert(num_threads > 0);
35  assert(num_threads <= kMaxNumThreads);
36  total_num_alloc = atoi(argv[2]);
37  assert(total_num_alloc > 0);
38  printf("%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(&tid[i], 0, thread_fun, 0);
42  pthread_mutex_lock(&mutex);
43  go = true;
44  pthread_cond_broadcast(&cond);
45  pthread_mutex_unlock(&mutex);
46  for (int i = 0; i < num_threads; i++) pthread_join(tid[i], 0);
47  return 0;
48}
49