| 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 "test/IntegrationTest/test.h" |
| 12 | |
| 13 | #include <pthread.h> |
| 14 | #include <stdint.h> // uintptr_t |
| 15 | |
| 16 | static constexpr int thread_count = 1000; |
| 17 | static int counter = 0; |
| 18 | static void *thread_func(void *) { |
| 19 | ++counter; |
| 20 | return nullptr; |
| 21 | } |
| 22 | |
| 23 | void create_and_join() { |
| 24 | for (counter = 0; counter <= thread_count;) { |
| 25 | pthread_t thread; |
| 26 | int old_counter_val = counter; |
| 27 | ASSERT_EQ( |
| 28 | LIBC_NAMESPACE::pthread_create(&thread, nullptr, thread_func, nullptr), |
| 29 | 0); |
| 30 | |
| 31 | // Start with a retval we dont expect. |
| 32 | void *retval = reinterpret_cast<void *>(thread_count + 1); |
| 33 | ASSERT_EQ(LIBC_NAMESPACE::pthread_join(thread, &retval), 0); |
| 34 | ASSERT_EQ(uintptr_t(retval), uintptr_t(nullptr)); |
| 35 | ASSERT_EQ(counter, old_counter_val + 1); |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | static void *return_arg(void *arg) { return arg; } |
| 40 | |
| 41 | void spawn_and_join() { |
| 42 | pthread_t thread_list[thread_count]; |
| 43 | int args[thread_count]; |
| 44 | |
| 45 | for (int i = 0; i < thread_count; ++i) { |
| 46 | args[i] = i; |
| 47 | ASSERT_EQ(LIBC_NAMESPACE::pthread_create(thread_list + i, nullptr, |
| 48 | return_arg, args + i), |
| 49 | 0); |
| 50 | } |
| 51 | |
| 52 | for (int i = 0; i < thread_count; ++i) { |
| 53 | // Start with a retval we dont expect. |
| 54 | void *retval = reinterpret_cast<void *>(thread_count + 1); |
| 55 | ASSERT_EQ(LIBC_NAMESPACE::pthread_join(thread_list[i], &retval), 0); |
| 56 | ASSERT_EQ(*reinterpret_cast<int *>(retval), i); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | TEST_MAIN() { |
| 61 | create_and_join(); |
| 62 | spawn_and_join(); |
| 63 | return 0; |
| 64 | } |
| 65 | |