blob: af2f961ed4ef470312a071fd43c33ebb67b20466 [file] [log] [blame]
Prabir Pradhand5678112023-05-18 01:57:10 +00001/*
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 "../SyncQueue.h"
18
19#include <gtest/gtest.h>
20#include <thread>
21
22namespace android {
23
24// --- SyncQueueTest ---
25
26// Validate basic pop and push operation.
27TEST(SyncQueueTest, AddAndRemove) {
28 SyncQueue<int> queue;
29
30 queue.push(1);
31 ASSERT_EQ(queue.pop(), 1);
32
33 queue.push(3);
34 ASSERT_EQ(queue.pop(), 3);
35
36 ASSERT_EQ(std::nullopt, queue.pop());
37}
38
39// Make sure the queue maintains FIFO order.
40// Add elements and remove them, and check the order.
41TEST(SyncQueueTest, isFIFO) {
42 SyncQueue<int> queue;
43
44 constexpr int numItems = 10;
45 for (int i = 0; i < numItems; i++) {
46 queue.push(static_cast<int>(i));
47 }
48 for (int i = 0; i < numItems; i++) {
49 ASSERT_EQ(queue.pop(), static_cast<int>(i));
50 }
51}
52
53TEST(SyncQueueTest, AllowsMultipleThreads) {
54 SyncQueue<int> queue;
55
56 // Test with a large number of items to increase likelihood that threads overlap
57 constexpr int numItems = 100;
58
59 // Fill queue from a different thread
60 std::thread fillQueue([&queue]() {
61 for (int i = 0; i < numItems; i++) {
62 queue.push(static_cast<int>(i));
63 }
64 });
65
66 // Make sure all elements are received in correct order
67 for (int i = 0; i < numItems; i++) {
68 // Since popping races with the thread that's filling the queue,
69 // keep popping until we get something back
70 std::optional<int> popped;
71 do {
72 popped = queue.pop();
73 } while (!popped);
74 ASSERT_EQ(popped, static_cast<int>(i));
75 }
76
77 fillQueue.join();
78}
79
80} // namespace android