Wednesday, December 7, 2016

lock_guard vs shared_lock is exclusive vs. shared in c++14

(1) C++ 14/17 rare write mostly read is Microsoft  ReaderWriter Lock concept.
(2) lock_guard also aware of how many shared lock in effect before exclude locking so some overhead.
(3) shared_lock can try timed 1 ms to see if writing in progress and give up
(4) both lock_guard and shared_lock construct on the same shared_timed_mutex


std::map<std::string, std::string> _map;
std::shared_timed_mutex m;

std::string find_entry(std::string s)
{
 std::shared_lock<std::shared_timed_mutex> guard(m);
 auto it = _map.find(s);
 if (it == _map.end())
 {
  throw runtime_error("not found");
 }
 return it->second;
}
void add_entry(std::string key,::string s)
{
 std::lock_guard<std::shared_timed_mutex> guard(m);
 _map.insert(make_pair(key,s));
}

void do_work_if_get_lock_in_1sec()
{
 shared_lock<shared_timed_mutex> sl(m, std::chrono::seconds(1));
 if (!sl.owns_lock())
  return;
 //do work after getting lock
}

No comments:

Post a Comment