gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 12:33:54 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com