Let\'s say I have a multithreaded C++ program that handles requests in the form of a function call to handleRequest(string key). Each call to handleRequest
After thinking about it, another approach might go something like this:
handleRequest, create a Callback that does the actual work.multimap global_key_map , protected by a mutex.key is already being processed, it adds its Callback* to the global_key_map and returns.Implemented something like this:
LockAndCall(string key, Callback* callback) {
global_lock.Lock();
if (global_key_map.contains(key)) {
iterator iter = global_key_map.insert(key, callback);
while (true) {
global_lock.Unlock();
iter->second->Call();
global_lock.Lock();
global_key_map.erase(iter);
iter = global_key_map.find(key);
if (iter == global_key_map.end()) {
global_lock.Unlock();
return;
}
}
} else {
global_key_map.insert(key, callback);
global_lock.Unlock();
}
}
This has the advantage of freeing up threads that would otherwise be waiting for a key lock, but apart from that it's pretty much the same as the naive solution I posted in the question.
It could be combined with the answers given by Mike B and Constantin, though.