1 // jemalloc C++ threaded test 2 // Author: Rustam Abdullaev 3 // Public Domain 4 5 #include <atomic> 6 #include <functional> 7 #include <future> 8 #include <random> 9 #include <thread> 10 #include <vector> 11 #include <stdio.h> 12 #include <jemalloc/jemalloc.h> 13 14 using std::vector; 15 using std::thread; 16 using std::uniform_int_distribution; 17 using std::minstd_rand; 18 19 int test_threads() { 20 je_malloc_conf = "narenas:3"; 21 int narenas = 0; 22 size_t sz = sizeof(narenas); 23 je_mallctl("opt.narenas", (void *)&narenas, &sz, NULL, 0); 24 if (narenas != 3) { 25 printf("Error: unexpected number of arenas: %d\n", narenas); 26 return 1; 27 } 28 static const int sizes[] = { 7, 16, 32, 60, 91, 100, 120, 144, 169, 199, 255, 400, 670, 900, 917, 1025, 3333, 5190, 13131, 49192, 99999, 123123, 255265, 2333111 }; 29 static const int numSizes = (int)(sizeof(sizes) / sizeof(sizes[0])); 30 vector<thread> workers; 31 static const int numThreads = narenas + 1, numAllocsMax = 25, numIter1 = 50, numIter2 = 50; 32 je_malloc_stats_print(NULL, NULL, NULL); 33 size_t allocated1; 34 size_t sz1 = sizeof(allocated1); 35 je_mallctl("stats.active", (void *)&allocated1, &sz1, NULL, 0); 36 printf("\nPress Enter to start threads...\n"); 37 getchar(); 38 printf("Starting %d threads x %d x %d iterations...\n", numThreads, numIter1, numIter2); 39 for (int i = 0; i < numThreads; i++) { 40 workers.emplace_back([tid=i]() { 41 uniform_int_distribution<int> sizeDist(0, numSizes - 1); 42 minstd_rand rnd(tid * 17); 43 uint8_t* ptrs[numAllocsMax]; 44 int ptrsz[numAllocsMax]; 45 for (int i = 0; i < numIter1; ++i) { 46 thread t([&]() { 47 for (int i = 0; i < numIter2; ++i) { 48 const int numAllocs = numAllocsMax - sizeDist(rnd); 49 for (int j = 0; j < numAllocs; j += 64) { 50 const int x = sizeDist(rnd); 51 const int sz = sizes[x]; 52 ptrsz[j] = sz; 53 ptrs[j] = (uint8_t*)je_malloc(sz); 54 if (!ptrs[j]) { 55 printf("Unable to allocate %d bytes in thread %d, iter %d, alloc %d. %d\n", sz, tid, i, j, x); 56 exit(1); 57 } 58 for (int k = 0; k < sz; k++) 59 ptrs[j][k] = tid + k; 60 } 61 for (int j = 0; j < numAllocs; j += 64) { 62 for (int k = 0, sz = ptrsz[j]; k < sz; k++) 63 if (ptrs[j][k] != (uint8_t)(tid + k)) { 64 printf("Memory error in thread %d, iter %d, alloc %d @ %d : %02X!=%02X\n", tid, i, j, k, ptrs[j][k], (uint8_t)(tid + k)); 65 exit(1); 66 } 67 je_free(ptrs[j]); 68 } 69 } 70 }); 71 t.join(); 72 } 73 }); 74 } 75 for (thread& t : workers) { 76 t.join(); 77 } 78 je_malloc_stats_print(NULL, NULL, NULL); 79 size_t allocated2; 80 je_mallctl("stats.active", (void *)&allocated2, &sz1, NULL, 0); 81 size_t leaked = allocated2 - allocated1; 82 printf("\nDone. Leaked: %zd bytes\n", leaked); 83 bool failed = leaked > 65536; // in case C++ runtime allocated something (e.g. iostream locale or facet) 84 printf("\nTest %s!\n", (failed ? "FAILED" : "successful")); 85 printf("\nPress Enter to continue...\n"); 86 getchar(); 87 return failed ? 1 : 0; 88 } 89