1 /*
2  * Copyright (C) 2017 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 #ifndef ANDROID_HARDWARE_BROADCASTRADIO_VTS_POINTER_UTILS
17 #define ANDROID_HARDWARE_BROADCASTRADIO_VTS_POINTER_UTILS
18 
19 #include <chrono>
20 #include <thread>
21 
22 using namespace std::chrono_literals;
23 
24 namespace android {
25 namespace hardware {
26 namespace broadcastradio {
27 namespace vts {
28 
29 /**
30  * Clears strong pointer and waits until the object gets destroyed.
31  *
32  * @param ptr The pointer to get cleared.
33  * @param timeout Time to wait for other references.
34  */
35 template <typename T>
clearAndWait(sp<T> & ptr,std::chrono::milliseconds timeout)36 static void clearAndWait(sp<T>& ptr, std::chrono::milliseconds timeout) {
37     using std::chrono::steady_clock;
38 
39     constexpr auto step = 10ms;
40 
41     wp<T> wptr = ptr;
42     ptr.clear();
43 
44     auto limit = steady_clock::now() + timeout;
45     while (wptr.promote() != nullptr) {
46         if (steady_clock::now() + step > limit) {
47             FAIL() << "Pointer was not released within timeout";
48             break;
49         }
50         std::this_thread::sleep_for(step);
51     }
52 }
53 
54 }  // namespace vts
55 }  // namespace broadcastradio
56 }  // namespace hardware
57 }  // namespace android
58 
59 #endif  // ANDROID_HARDWARE_BROADCASTRADIO_VTS_POINTER_UTILS
60