How do I use an arbitrary string as a lock in C++?

前端 未结 6 1902
半阙折子戏
半阙折子戏 2021-02-04 15:15

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

6条回答
  •  猫巷女王i
    2021-02-04 15:55

    After thinking about it, another approach might go something like this:

    • In handleRequest, create a Callback that does the actual work.
    • Create a multimap global_key_map, protected by a mutex.
    • If a thread sees that key is already being processed, it adds its Callback* to the global_key_map and returns.
    • Otherwise, it calls its callback immediately, and then calls the callbacks that have shown up in the meantime for the same key.

    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.

提交回复
热议问题