Josh Gao | 9efe321 | 2016-02-09 14:59:09 -0800 | [diff] [blame] | 1 | /* |
Josh Gao | 0f80e09 | 2016-02-12 11:33:53 -0800 | [diff] [blame] | 2 | * Copyright (C) 2016 The Android Open Source Project |
Josh Gao | 9efe321 | 2016-02-09 14:59:09 -0800 | [diff] [blame] | 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 | #include <unistd.h> |
| 19 | #include <atomic> |
| 20 | |
| 21 | #include "sysdeps.h" |
| 22 | |
Josh Gao | 382ea6e | 2016-02-12 14:31:15 -0800 | [diff] [blame] | 23 | static void increment_atomic_int(void* c) { |
Josh Gao | 9efe321 | 2016-02-09 14:59:09 -0800 | [diff] [blame] | 24 | sleep(1); |
| 25 | reinterpret_cast<std::atomic<int>*>(c)->fetch_add(1); |
Josh Gao | 9efe321 | 2016-02-09 14:59:09 -0800 | [diff] [blame] | 26 | } |
| 27 | |
| 28 | TEST(sysdeps_thread, smoke) { |
| 29 | std::atomic<int> counter(0); |
| 30 | |
| 31 | for (int i = 0; i < 100; ++i) { |
| 32 | ASSERT_TRUE(adb_thread_create(increment_atomic_int, &counter)); |
| 33 | } |
| 34 | |
| 35 | sleep(2); |
| 36 | ASSERT_EQ(100, counter.load()); |
| 37 | } |
| 38 | |
| 39 | TEST(sysdeps_thread, join) { |
| 40 | std::atomic<int> counter(0); |
| 41 | std::vector<adb_thread_t> threads(500); |
| 42 | for (size_t i = 0; i < threads.size(); ++i) { |
| 43 | ASSERT_TRUE(adb_thread_create(increment_atomic_int, &counter, &threads[i])); |
| 44 | } |
| 45 | |
| 46 | int current = counter.load(); |
| 47 | ASSERT_GE(current, 0); |
| 48 | // Make sure that adb_thread_create actually creates threads, and doesn't do something silly |
| 49 | // like synchronously run the function passed in. The sleep in increment_atomic_int should be |
| 50 | // enough to keep this from being flakey. |
| 51 | ASSERT_LT(current, 500); |
| 52 | |
| 53 | for (const auto& thread : threads) { |
| 54 | ASSERT_TRUE(adb_thread_join(thread)); |
| 55 | } |
| 56 | |
| 57 | ASSERT_EQ(500, counter.load()); |
| 58 | } |
Josh Gao | 382ea6e | 2016-02-12 14:31:15 -0800 | [diff] [blame] | 59 | |
| 60 | TEST(sysdeps_thread, exit) { |
| 61 | adb_thread_t thread; |
| 62 | ASSERT_TRUE(adb_thread_create( |
| 63 | [](void*) { |
| 64 | adb_thread_exit(); |
| 65 | for (;;) continue; |
| 66 | }, |
| 67 | nullptr, &thread)); |
| 68 | ASSERT_TRUE(adb_thread_join(thread)); |
| 69 | } |