xref: /aosp_15_r20/external/llvm-libc/test/integration/src/pthread/pthread_equal_test.cpp (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===-- Tests for pthread_equal -------------------------------------------===//
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_equal.h"
11 #include "src/pthread/pthread_join.h"
12 #include "src/pthread/pthread_mutex_destroy.h"
13 #include "src/pthread/pthread_mutex_init.h"
14 #include "src/pthread/pthread_mutex_lock.h"
15 #include "src/pthread/pthread_mutex_unlock.h"
16 #include "src/pthread/pthread_self.h"
17 
18 #include "test/IntegrationTest/test.h"
19 
20 #include <pthread.h>
21 #include <stdint.h> // uintptr_t
22 
23 pthread_t child_thread;
24 pthread_mutex_t mutex;
25 
child_func(void * arg)26 static void *child_func(void *arg) {
27   LIBC_NAMESPACE::pthread_mutex_lock(&mutex);
28   int *ret = reinterpret_cast<int *>(arg);
29   auto self = LIBC_NAMESPACE::pthread_self();
30   *ret = LIBC_NAMESPACE::pthread_equal(child_thread, self);
31   LIBC_NAMESPACE::pthread_mutex_unlock(&mutex);
32   return nullptr;
33 }
34 
TEST_MAIN()35 TEST_MAIN() {
36   // We init and lock the mutex so that we guarantee that the child thread is
37   // waiting after startup.
38   ASSERT_EQ(LIBC_NAMESPACE::pthread_mutex_init(&mutex, nullptr), 0);
39   ASSERT_EQ(LIBC_NAMESPACE::pthread_mutex_lock(&mutex), 0);
40 
41   auto main_thread = LIBC_NAMESPACE::pthread_self();
42 
43   // The idea here is that, we start a child thread which will immediately
44   // wait on |mutex|. The main thread will update the global |child_thread| var
45   // and unlock |mutex|. This will give the child thread a chance to compare
46   // the result of pthread_self with the |child_thread|. The result of the
47   // comparison is returned in the thread arg.
48   int result = 0;
49   pthread_t th;
50   ASSERT_EQ(LIBC_NAMESPACE::pthread_create(&th, nullptr, child_func, &result),
51             0);
52   // This new thread should of course not be equal to the main thread.
53   ASSERT_EQ(LIBC_NAMESPACE::pthread_equal(th, main_thread), 0);
54 
55   // Set the |child_thread| global var and unlock to allow the child to perform
56   // the comparison.
57   child_thread = th;
58   ASSERT_EQ(LIBC_NAMESPACE::pthread_mutex_unlock(&mutex), 0);
59 
60   void *retval;
61   ASSERT_EQ(LIBC_NAMESPACE::pthread_join(th, &retval), 0);
62   ASSERT_EQ(uintptr_t(retval), uintptr_t(nullptr));
63   // The child thread should see that pthread_self return value is the same as
64   // |child_thread|.
65   ASSERT_NE(result, 0);
66 
67   LIBC_NAMESPACE::pthread_mutex_destroy(&mutex);
68   return 0;
69 }
70