xref: /llvm-project/libc/test/integration/src/pthread/pthread_test.cpp (revision 0a537a1299b03126b23938c36edbfd2edbea44c1)
1 //===-- Tests for pthread_t -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "src/pthread/pthread_create.h"
10 #include "src/pthread/pthread_join.h"
11 #include "utils/IntegrationTest/test.h"
12 
13 #include <pthread.h>
14 
15 static constexpr int thread_count = 1000;
16 static int counter = 0;
17 static void *thread_func(void *) {
18   ++counter;
19   return nullptr;
20 }
21 
22 void create_and_join() {
23   for (counter = 0; counter <= thread_count;) {
24     pthread_t thread;
25     int old_counter_val = counter;
26     ASSERT_EQ(
27         __llvm_libc::pthread_create(&thread, nullptr, thread_func, nullptr), 0);
28 
29     // Start with a retval we dont expect.
30     void *retval = reinterpret_cast<void *>(thread_count + 1);
31     ASSERT_EQ(__llvm_libc::pthread_join(thread, &retval), 0);
32     ASSERT_EQ(uintptr_t(retval), uintptr_t(nullptr));
33     ASSERT_EQ(counter, old_counter_val + 1);
34   }
35 }
36 
37 static void *return_arg(void *arg) { return arg; }
38 
39 void spawn_and_join() {
40   pthread_t thread_list[thread_count];
41   int args[thread_count];
42 
43   for (int i = 0; i < thread_count; ++i) {
44     args[i] = i;
45     ASSERT_EQ(__llvm_libc::pthread_create(thread_list + i, nullptr, return_arg,
46                                           args + i),
47               0);
48   }
49 
50   for (int i = 0; i < thread_count; ++i) {
51     // Start with a retval we dont expect.
52     void *retval = reinterpret_cast<void *>(thread_count + 1);
53     ASSERT_EQ(__llvm_libc::pthread_join(thread_list[i], &retval), 0);
54     ASSERT_EQ(*reinterpret_cast<int *>(retval), i);
55   }
56 }
57 
58 int main() {
59   create_and_join();
60   spawn_and_join();
61   return 0;
62 }
63