| … | … | @@ -174,6 +174,25 @@ public: |
| 174 | 174 | return insert_impl([&]() { the_set.insert(std::move(item)); }); |
| 175 | 175 | } |
| 176 | 176 | |
| 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 | |
| 177 | 196 | /// Remove the Element from the set. Return number of Elements |
| 178 | 197 | /// removed, i.e. 1 or 0, depending on whether the item was found |
| 179 | 198 | /// (or not) in the set. |