1 /*
2  * Copyright 2023 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 #include "test/fake/fake_thread.h"
18 
19 #include <bluetooth/log.h>
20 #include <gtest/gtest.h>
21 #include <stdlib.h>
22 
23 #include <mutex>
24 
25 struct quiesce_t {
26   thread_t* thread;
27 };
28 
is_running() const29 bool thread_t::is_running() const {
30   std::lock_guard<decltype(is_running_lock_)> lock(is_running_lock_);
31   return is_running_ == State::RUNNING;
32 }
33 
set_state(State state)34 void thread_t::set_state(State state) {
35   std::lock_guard<decltype(is_running_lock_)> lock(is_running_lock_);
36   is_running_ = state;
37 }
38 
quiesce()39 void thread_t::quiesce() {
40   quiesce_t* quiesce = static_cast<quiesce_t*>(calloc(sizeof(quiesce_t), 1));
41   bluetooth::log::assert_that(quiesce != nullptr,
42                               "assert failed: quiesce != nullptr");
43   quiesce->thread = this;
44   thread_post(
45       this,
46       [](void* context) {
47         quiesce_t* quiesce = static_cast<quiesce_t*>(context);
48         quiesce->thread->set_state(thread_t::State::QUIESCE);
49       },
50       static_cast<void*>(quiesce));
51 
52   // Wait for thread to stop
53   thread_finish_semaphore.wait();
54   // thread is queiesced so return
55 }
56 
notify_finished()57 void thread_t::notify_finished() { thread_finish_semaphore.notify(); }
58