From 2fabf8d8dbdaf8670c7b6c5ad6b9316d61c89531 Mon Sep 17 00:00:00 2001 From: EntireTwix Date: Sun, 11 Apr 2021 14:28:30 -0700 Subject: [PATCH] :racehorse: made AllUsers more effecient --- include/bank.hpp | 38 +++++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/include/bank.hpp b/include/bank.hpp index e2147a9..f56a905 100644 --- a/include/bank.hpp +++ b/include/bank.hpp @@ -29,14 +29,18 @@ private: */ std::shared_mutex send_funds_l; + bool size_lock_flag = true; + Json::Value temp; + public: std::string admin_pass; bool AddUser(const std::string &name, std::string &&init_pass) { std::unique_lock lock{size_lock}; + size_lock_flag = true; return users.try_emplace_l( - name, [](User &) {}, std::move(init_pass)); + name, [this](User &) { size_lock_flag = false; }, std::move(init_pass)); } bool AdminAddUser(const std::string &attempt, std::string &&name, uint_fast32_t init_bal, std::string &&init_pass) { @@ -47,18 +51,23 @@ public: state = users.try_emplace_l( name, [](User &) {}, init_bal, std::move(init_pass)); } + size_lock_flag += state; return state; } bool DelUser(const std::string &name, const std::string &attempt) { std::unique_lock lock{size_lock}; - return users.erase_if(name, [&attempt](const User &u) { return (attempt == u.password); }); + bool state = users.erase_if(name, [&attempt](const User &u) { return (attempt == u.password); }); + size_lock_flag += state; + return state; } bool AdminDelUser(const std::string &name, const std::string &attempt) { std::unique_lock lock{size_lock}; - return users.erase_if(name, [this, &attempt](const User &) { return (admin_pass == attempt); }); + bool state = users.erase_if(name, [this, &attempt](const User &) { return (admin_pass == attempt); }); + size_lock_flag += state; + return state; } bool SendFunds(const std::string &a_name, const std::string &b_name, uint_fast32_t amount, const std::string &attempt) @@ -144,13 +153,24 @@ public: Json::Value AllUsers() { - Json::Value temp; - Json::UInt i = 0; - std::shared_lock lock{size_lock}; //gives readers of users the lock - for (const auto &u : users) + bool temp_flag = false; { - //we know it contains this key but we call this func to grab mutex - temp[i++] = u.first; + std::shared_lock lock{size_lock}; + temp_flag = size_lock_flag; + } + + if (!temp_flag) + { + temp = Json::Value(); + Json::UInt i = 0; + for (const auto &u : users) + { + //we know it contains this key but we call this func to grab mutex + temp[i++] = u.first; + } + size_lock.unlock_shared(); + std::unique_lock lock{size_lock}; + size_lock_flag = false; } return temp; }