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