forked from LadybirdBrowser/ladybird
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestThread.cpp
73 lines (58 loc) · 1.88 KB
/
TestThread.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* Copyright (c) 2021, Spencer Dixon <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Time.h>
#include <LibTest/TestCase.h>
#include <LibThreading/Thread.h>
#include <unistd.h>
using namespace AK::TimeLiterals;
static void sleep_until_thread_exits(Threading::Thread const& thread)
{
static constexpr auto delay = 20_ms;
for (auto i = 0; i < 100; ++i) {
if (thread.has_exited())
return;
usleep(delay.to_microseconds());
}
FAIL("Timed out waiting for thread to exit");
}
TEST_CASE(threads_can_detach)
{
Atomic<int> should_be_42 = 0;
auto thread = Threading::Thread::construct([&should_be_42]() {
usleep(10 * 1000);
should_be_42 = 42;
return 0;
});
thread->start();
thread->detach();
sleep_until_thread_exits(*thread);
EXPECT(should_be_42 == 42);
}
TEST_CASE(detached_threads_do_not_need_to_be_joined)
{
Atomic<bool> should_exit { false };
auto thread = Threading::Thread::construct([&]() {
while (!should_exit.load())
usleep(10 * 1000);
return 0;
});
thread->start();
thread->detach();
// Because of how the crash test forks and removes the thread, we can't use that to verify that join() crashes. Instead, we check the join crash condition ourselves.
EXPECT(!thread->needs_to_be_joined());
// FIXME: Dropping a running thread crashes because of the Function destructor. For now, force the detached thread to exit.
should_exit.store(true);
sleep_until_thread_exits(*thread);
}
TEST_CASE(join_dead_thread)
{
auto thread = Threading::Thread::construct([&]() { return 0 /*nullptr*/; });
thread->start();
// The thread should have exited by then.
sleep_until_thread_exits(*thread);
auto join_result = TRY_OR_FAIL(thread->join<int*>());
EXPECT_EQ(join_result, static_cast<int*>(0));
}