c++ - 当一个线程锁定一张大 map 时如何避免卡住其他线程

标签 c++ linux multithreading stl mutex

如何避免卡住试图访问被当前线程锁定的同一 map 的其他线程?看下面的代码:

           //pseudo code
           std::map<string, CSomeClass* > gBigMap;
           void AccessMapForWriting(string aString){
                 pthread_mutex_lock(&MapLock);

                 CSomeClass* obj = gBigMap[aString];
                 if (obj){
                       gBigMap.erase(aString);

                       delete obj;
                       obj = NULL;
                 }


                 pthread_mutex_unlock(&MapLock);
           }

           void AccessMapForReading(string aString){
                 pthread_mutex_lock(&MapLock);
                 CSomeClass* obj = gBigMap[aString];

                 //below code consumes much time
                 //sometimes it even sleeps for milliseconds
                 if (obj){
                     obj->TimeConsumingOperation();
                 }

                 pthread_mutex_unlock(&MapLock);
           }

           //other threads will also call 
           //the same function -- AccessMap
           void *OtherThreadFunc(void *){
                 //call AccessMap here
           }

最佳答案

考虑改用读写锁,pthread_rwlock_t 还有一些细节here 它说

"Using a normal mutex, when a thread obtains the mutex all other threads are forced to block until that mutex is released by the owner.

What about the situation where the vast majority of threads are simply reading the data? If this is the case then we should not care if there is 1 or up to N readers in the critical section at the same time. In fact the only time we would normally care about exclusive ownership is when a writer needs access to the code section."

关于c++ - 当一个线程锁定一张大 map 时如何避免卡住其他线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18078200/

相关文章:

c++ - 包装代码以避免重复的技术?

linux - 启动时 Jiffies 不为零

linux - 拦截所有二进制文件的打开系统调用

.net - .NET:以挂起状态启动线程

c++ - 如果我想使用 "a = {x, y};",要重载什么运算符

C++ - 结构与类

linux - 如何计算从同一父进程派生的进程使用的总物理内存?

java - 如何在另一个线程中重新抛出异常以捕获 block

multithreading - 如何在没有Arc的线程中使用互斥锁?

c++ - 如何为非静态容器中的值编写值参数化测试?