blob: 2fe63b7b3bae60c2c0bf12f5f29f8f2fa62be1dc [file] [log] [blame]
Mike Yuc6d4c6b2019-03-14 15:14:44 +08001/*
2 * Copyright (C) 2019 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 <gtest/gtest.h>
18
19#include "netdutils/ThreadUtil.h"
20
21namespace android {
22namespace netdutils {
23
24namespace {
25
26class NoopRun {
27 public:
28 NoopRun() { instanceNum++; }
29 ~NoopRun() { instanceNum--; }
30
31 void run() {}
32
33 static bool waitForAllReleased(int timeoutMs) {
34 constexpr int intervalMs = 20;
35 int limit = timeoutMs / intervalMs;
36 for (int i = 1; i < limit; i++) {
37 if (instanceNum == 0) {
38 return true;
39 }
40 usleep(intervalMs * 1000);
41 }
42 return false;
43 }
44
45 // To track how many instances are alive.
46 static std::atomic<int> instanceNum;
47};
48
49std::atomic<int> NoopRun::instanceNum;
50
51} // namespace
52
53TEST(ThreadUtilTest, objectReleased) {
54 NoopRun::instanceNum = 0;
55 NoopRun* obj = new NoopRun();
56 EXPECT_EQ(1, NoopRun::instanceNum);
57 threadLaunch(obj);
58
59 // Wait for the object released along with the thread exited.
60 EXPECT_TRUE(NoopRun::waitForAllReleased(1000));
61 EXPECT_EQ(0, NoopRun::instanceNum);
62}
63
64} // namespace netdutils
65} // namespace android