xref: /llvm-project/libc/test/integration/src/__support/threads/thread_detach_test.cpp (revision 142afde0eba4940f2b331274e9a3535fee960f35)
1 //===-- Tests for thread detach functionality -----------------------------===//
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/__support/threads/mutex.h"
10 #include "src/__support/threads/thread.h"
11 #include "test/IntegrationTest/test.h"
12 
13 LIBC_NAMESPACE::Mutex mutex(/*timed=*/false, /*recursive=*/false,
14                             /*robust=*/false, /*pshared=*/false);
15 
func(void *)16 int func(void *) {
17   mutex.lock();
18   mutex.unlock();
19   return 0;
20 }
21 
detach_simple_test()22 void detach_simple_test() {
23   mutex.lock();
24   LIBC_NAMESPACE::Thread th;
25   th.run(func, nullptr, nullptr, 0);
26 
27   // Since |mutex| is held by the current thread, we guarantee that
28   // th is running and hence it is safe to detach. Since the thread is
29   // still running, it should be simple detach.
30   ASSERT_EQ(th.detach(), int(LIBC_NAMESPACE::DetachType::SIMPLE));
31 
32   // We will release |mutex| now to let the thread finish an cleanup itself.
33   mutex.unlock();
34 }
35 
detach_cleanup_test()36 void detach_cleanup_test() {
37   mutex.lock();
38   LIBC_NAMESPACE::Thread th;
39   ASSERT_EQ(0, th.run(func, nullptr));
40 
41   // Since |mutex| is held by the current thread, we will release it
42   // to let |th| run.
43   mutex.unlock();
44 
45   // We will wait for |th| to finish. Since it is a joinable thread,
46   // we can wait on it safely.
47   th.wait();
48 
49   // Since |th| is now finished, detaching should cleanup the thread
50   // resources.
51   ASSERT_EQ(th.detach(), int(LIBC_NAMESPACE::DetachType::CLEANUP));
52 }
53 
TEST_MAIN()54 TEST_MAIN() {
55   detach_simple_test();
56   detach_cleanup_test();
57   return 0;
58 }
59