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

前端 未结 6 1889
半阙折子戏
半阙折子戏 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条回答
  •  一向
    一向 (楼主)
    2021-02-04 15:45

    Perhaps an std::map would be what you want, where MutexType is the type of the mutex you want. You will probably have to wrap accesses to the map in another mutex in order to ensure that no other thread is inserting at the same time (and remember to perform the check again after the mutex is locked to ensure that another thread didn't add the key while waiting on the mutex!).

    The same principle could apply to any other synchronization method, such as a critical section.

提交回复
热议问题