OverviewFilesCommitsIssuesDocsReleasesPeers

opencog-cogutil commits / 64dca90

Add an atomic try_insert into concurrent_set
64dca9083dcfa485dcb70fd6fe7ba1f80e0f4082
by Linas Vepstas <linasvepstas@gmail.com> · 2025-12-21T01:18:47.000Z

Changed files (1) +19 -0

opencog/util/concurrent_set.h +19 -0
……@@ -174,6 +174,25 @@ public:
174174 return insert_impl([&]() { the_set.insert(std::move(item)); });
175175 }
176176
177 /// Atomic transition from empty to non-empty set. Useful for
178 /// implementing homogenous sets, where set contents are determined
179 /// by the first element to be inserted; the goal is to avoid two
180 /// threads racing to insert the first element.
181 ///
182 /// If the set is empty, insert the item and return std::nullopt.
183 /// If the set is non-empty, return a representative from the set;
184 /// The insert is NOT performed.
185 std::optional<Element> try_insert(Element&& item)
186 {
187 std::lock_guard<std::mutex> lock(the_mutex);
188 if (the_set.empty())
189 {
190 the_set.insert(std::move(item));
191 return std::nullopt;
192 }
193 return *the_set.begin();
194 }
195
177196 /// Remove the Element from the set. Return number of Elements
178197 /// removed, i.e. 1 or 0, depending on whether the item was found
179198 /// (or not) in the set.