如何避免卡住试图访问被当前线程锁定的同一 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/