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