1 /* 2 * Copyright (c) 2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #include <string> 17 #include <thread> 18 #include "gtest/gtest.h" 19 #define private public 20 #include "CallbackQueue.h" 21 using namespace std; 22 23 namespace { TEST(CallbackQueueTest,AddCallbackTest)24 TEST(CallbackQueueTest, AddCallbackTest) 25 { 26 CallbackQueue queue; 27 bool callbackCalled = false; 28 29 // 添加回调函数到队列中 30 queue.AddCallback([&callbackCalled]() { 31 callbackCalled = true; 32 }); 33 34 // 执行队列中的回调函数 35 queue.ConsumingCallback(); 36 37 // 验证回调函数是否被调用 38 EXPECT_TRUE(callbackCalled); 39 } 40 TEST(CallbackQueueTest,ConsumingCallbackTest)41 TEST(CallbackQueueTest, ConsumingCallbackTest) 42 { 43 CallbackQueue queue; 44 45 // 添加多个回调函数到队列中 46 for (int i = 0; i < 5; ++i) { 47 queue.AddCallback([]() { 48 std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟耗时操作 49 }); 50 } 51 52 // 启动多个线程同时执行 ConsumingCallback() 方法 53 std::vector<std::thread> threads; 54 for (int i = 0; i < 3; ++i) { 55 threads.emplace_back([&queue]() { 56 queue.ConsumingCallback(); 57 }); 58 } 59 60 // 等待所有线程执行完成 61 for (auto& thread : threads) { 62 thread.join(); 63 } 64 65 // 验证队列中的回调函数是否都被执行完毕 66 EXPECT_EQ(queue.callBackList.size(), 0); 67 } 68 }