1 // Test that threads are reused.
2 // On Android, pthread_* are in libc.so. So the `-lpthread` is not supported.
3 // Use `-pthread` so that its driver will DTRT (ie., ignore it).
4 // RUN: %clangxx_lsan %s -o %t -pthread && %run %t
5 
6 #include <assert.h>
7 #include <dirent.h>
8 #include <pthread.h>
9 #include <stdlib.h>
10 #include <unistd.h>
11 
12 // Number of threads to create. This value is greater than kMaxThreads in
13 // lsan_thread.cpp so that we can test that thread contexts are not being
14 // reused.
15 static const size_t kTestThreads = 10000;
16 
17 // Limit the number of simultaneous threads to avoid reaching the limit.
18 static const size_t kTestThreadsBatch = 100;
19 
20 void *null_func(void *args) {
21   return NULL;
22 }
23 
24 int count_threads() {
25   DIR *d = opendir("/proc/self/task");
26   assert(d);
27   int count = 0;
28   while (readdir(d))
29     ++count;
30   closedir(d);
31   assert(count);
32   return count;
33 }
34 
35 int main(void) {
36   for (size_t i = 0; i < kTestThreads; i += kTestThreadsBatch) {
37     for (size_t j = 0; j < kTestThreadsBatch; ++j) {
38       pthread_t thread;
39       assert(pthread_create(&thread, NULL, null_func, NULL) == 0);
40       pthread_detach(thread);
41     }
42     while (count_threads() > 10)
43       sched_yield();
44   }
45   return 0;
46 }
47