1 /*
2 * Copyright (C) 2024 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "jthread_tests"
18
19 #include <mediautils/jthread.h>
20
21 #include <gtest/gtest.h>
22
23 #include <atomic>
24
25 using namespace android::mediautils;
26
27 namespace {
TEST(jthread_tests,dtor)28 TEST(jthread_tests, dtor) {
29 std::atomic_int x = 0;
30 std::atomic_bool is_stopped = false;
31 {
32 auto jt = jthread([&](stop_token stok) {
33 while (!stok.stop_requested()) {
34 if (x.load() < std::numeric_limits<int>::max())
35 x++;
36 }
37 is_stopped = true;
38 });
39 while (x.load() < 1000)
40 ;
41 }
42 // Check we triggered a stop on dtor
43 ASSERT_TRUE(is_stopped.load());
44 // Check we actually ran
45 ASSERT_GE(x.load(), 1000);
46 }
TEST(jthread_tests,request_stop)47 TEST(jthread_tests, request_stop) {
48 std::atomic_int x = 0;
49 std::atomic_bool is_stopped = false;
50 auto jt = jthread([&](stop_token stok) {
51 while (!stok.stop_requested()) {
52 if (x.load() < std::numeric_limits<int>::max())
53 x++;
54 }
55 is_stopped = true;
56 });
57 while (x.load() < 1000)
58 ;
59 // request stop manually
60 ASSERT_TRUE(jt.request_stop());
61 // busy loop till thread acks
62 while (!is_stopped.load())
63 ;
64 // Check we triggered a stop on dtor
65 ASSERT_TRUE(is_stopped.load());
66 // Check we actually ran
67 ASSERT_GE(x.load(), 1000);
68 }
69
70 } // namespace
71