Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I use an arbitrary string as a lock in C++?
    text
    copied!<p>Let's say I have a multithreaded C++ program that handles requests in the form of a function call to <code>handleRequest(string key)</code>. Each call to <code>handleRequest</code> occurs in a separate thread, and there are an arbitrarily large number of possible values for <code>key</code>.</p> <p>I want the following behavior:</p> <ul> <li>Simultaneous calls to <code>handleRequest(key)</code> are serialized when they have the same value for <code>key</code>.</li> <li>Global serialization is minimized.</li> </ul> <p>The body of <code>handleRequest</code> might look like this:</p> <pre><code>void handleRequest(string key) { KeyLock lock(key); // Handle the request. } </code></pre> <p><b>Question:</b> How would I implement <code>KeyLock</code> to get the required behavior?</p> <p>A naive implementation might start off like this:</p> <pre><code>KeyLock::KeyLock(string key) { global_lock-&gt;Lock(); internal_lock_ = global_key_map[key]; if (internal_lock_ == NULL) { internal_lock_ = new Lock(); global_key_map[key] = internal_lock_; } global_lock-&gt;Unlock(); internal_lock_-&gt;Lock(); } KeyLock::~KeyLock() { internal_lock_-&gt;Unlock(); // Remove internal_lock_ from global_key_map iff no other threads are waiting for it. } </code></pre> <p>...but that requires a global lock at the beginning and end of each request, and the creation of a separate <code>Lock</code> object for each request. If contention is high between calls to <code>handleRequest</code>, that might not be a problem, but it could impose a lot of overhead if contention is low.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload