• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <gtest/gtest.h>
2 #include <thread>
3 #include <threads.h>
4 
5 using namespace testing::ext;
6 
7 class ThreadCallonceTest : public testing::Test {
SetUp()8     void SetUp() override {}
TearDown()9     void TearDown() override {}
10 };
11 
CallThrdSleep()12 static void CallThrdSleep()
13 {
14     timespec shrotTime = { .tv_sec = 1 };
15     thrd_sleep(&shrotTime, nullptr);
16 }
17 
18 /**
19  * @tc.name: call_once_001
20  * @tc.desc: Call the function twice in a single thread, ensuring that the function is only called once
21  *           Call the function twice in a row under multiple threads, ensuring that the function is only called once
22  * @tc.type: FUNC
23  * */
24 HWTEST_F(ThreadCallonceTest, call_once_001, TestSize.Level1)
25 {
26     timespec oTs;
27     EXPECT_EQ(TIME_UTC, timespec_get(&oTs, TIME_UTC));
28     int onceCall = ONCE_FLAG_INIT;
29     call_once(&onceCall, CallThrdSleep);
30     call_once(&onceCall, CallThrdSleep);
31 
__anon2e732d0c0102null32     std::thread([&onceCall] { call_once(&onceCall, CallThrdSleep); }).join();
33     timespec dTs;
34     EXPECT_EQ(TIME_UTC, timespec_get(&dTs, TIME_UTC));
35     EXPECT_GE(1, dTs.tv_sec - oTs.tv_sec);
36 }
37 
38 /**
39  * @tc.name: pthread_once_001
40  * @tc.desc: Call the function twice in a single thread, ensuring that the function is only called once
41  *           Call the function twice in a row under multiple threads, ensuring that the function is only called once
42  * @tc.type: FUNC
43  * */
44 HWTEST_F(ThreadCallonceTest, pthread_once_001, TestSize.Level1)
45 {
46     timespec oTs;
47     EXPECT_EQ(TIME_UTC, timespec_get(&oTs, TIME_UTC));
48     pthread_once_t onceCall = PTHREAD_ONCE_INIT;
49     EXPECT_EQ(0, pthread_once(&onceCall, CallThrdSleep));
50     EXPECT_EQ(0, pthread_once(&onceCall, CallThrdSleep));
51 
__anon2e732d0c0202null52     std::thread([&onceCall] { pthread_once(&onceCall, CallThrdSleep); }).join();
53     timespec dTs;
54     EXPECT_EQ(TIME_UTC, timespec_get(&dTs, TIME_UTC));
55     EXPECT_GE(1, dTs.tv_sec - oTs.tv_sec);
56 }