xref: /aosp_15_r20/external/federated-compute/fcp/base/process_unique_id_test.cc (revision 14675a029014e728ec732f129a32e299b2da0601)
1 /*
2  * Copyright 2020 Google LLC
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 "fcp/base/process_unique_id.h"
18 
19 #include <thread>  // NOLINT(build/c++11)
20 
21 #include "gtest/gtest.h"
22 #include "absl/container/flat_hash_set.h"
23 
24 namespace fcp {
25 
TEST(UniqueIdGeneratorTest,CallingNextYieldsDifferentIds)26 TEST(UniqueIdGeneratorTest, CallingNextYieldsDifferentIds) {
27   uint64_t id1 = ProcessUniqueId::Next().value();
28   uint64_t id2 = ProcessUniqueId::Next().value();
29   EXPECT_NE(id1, id2);
30 }
31 
TEST(UniqueIdGeneratorTest,MultipleThreads)32 TEST(UniqueIdGeneratorTest, MultipleThreads) {
33   const int n = 15;
34   std::thread threads[n];
35   uint64_t ids[n];
36   for (int i = 0; i < n; i++) {
37     threads[i] =
38         std::thread([&ids, i]() { ids[i] = ProcessUniqueId::Next().value(); });
39   }
40   for (int i = 0; i < n; i++) {
41     threads[i].join();
42   }
43   absl::flat_hash_set<uint64_t> id_set;
44   for (int i = 0; i < n; i++) {
45     bool inserted = id_set.insert(ids[i]).second;
46     EXPECT_TRUE(inserted);
47   }
48 }
49 
50 }  // namespace fcp
51