mirror of
https://github.com/bitcoin/bitcoin.git
synced 2025-11-11 22:50:59 +01:00
net: dedup and RAII-fy the creation of a copy of CConnman::vNodes
The following pattern was duplicated in CConnman: ```cpp lock create a copy of vNodes, add a reference to each one unlock ... use the copy ... lock release each node from the copy unlock ``` Put that code in a RAII helper that reduces it to: ```cpp create snapshot "snap" ... use the copy ... // release happens when "snap" goes out of scope ```
This commit is contained in:
37
src/net.h
37
src/net.h
@@ -1177,6 +1177,43 @@ private:
|
||||
*/
|
||||
std::vector<CService> m_onion_binds;
|
||||
|
||||
/**
|
||||
* RAII helper to atomically create a copy of `vNodes` and add a reference
|
||||
* to each of the nodes. The nodes are released when this object is destroyed.
|
||||
*/
|
||||
class NodesSnapshot
|
||||
{
|
||||
public:
|
||||
explicit NodesSnapshot(const CConnman& connman, bool shuffle)
|
||||
{
|
||||
{
|
||||
LOCK(connman.cs_vNodes);
|
||||
m_nodes_copy = connman.vNodes;
|
||||
for (auto& node : m_nodes_copy) {
|
||||
node->AddRef();
|
||||
}
|
||||
}
|
||||
if (shuffle) {
|
||||
Shuffle(m_nodes_copy.begin(), m_nodes_copy.end(), FastRandomContext{});
|
||||
}
|
||||
}
|
||||
|
||||
~NodesSnapshot()
|
||||
{
|
||||
for (auto& node : m_nodes_copy) {
|
||||
node->Release();
|
||||
}
|
||||
}
|
||||
|
||||
const std::vector<CNode*>& Nodes() const
|
||||
{
|
||||
return m_nodes_copy;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<CNode*> m_nodes_copy;
|
||||
};
|
||||
|
||||
friend struct CConnmanTest;
|
||||
friend struct ConnmanTestMsg;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user