thread 线程安全 unordered_map

C++11:基于std::unordered_map和共享锁构建线程安全的map

https://blog.csdn.net/10km/article/details/52072061

https://blog.csdn.net/10km/article/details/52067929

 

程序中经常需要缓存一些数据, 但是std::map 不是线程安全的

https://blog.csdn.net/chen802311/article/details/76793719

 

https://blog.csdn.net/10km/article/details/49641691

 

C++11中std::mutex的使用https://blog.csdn.net/fengbingchun/article/details/73521630

 

C++11 mutex方便的自解锁lock_guard

https://blog.csdn.net/xiaoyafang123/article/details/54137611

 

C++11 unordered_map 无序容器的使用

https://blog.csdn.net/haolipengzhanshen/article/details/51970348

 

https://blog.csdn.net/zengyubao1/article/details/80834628

C++ 11 std::unordered_map高级用法

https://blog.csdn.net/fcku_88/article/details/88353431

C++ std::unordered_map 用法详解

 

 

 

 

 

 

 

 

以下是对给定代码进行优化的建议: 1. 减少无效的查找操作:在代码中多次查找相同的 `memoryAddr`,可以考虑将查找结果保存到临时变量中,以避免重复查找。 2. 使用迭代器遍历容器元素:在代码中使用了下标遍历容器元素,可以考虑使用迭代器来遍历容器元素,以提高效率。 3. 减少不必要的对象创建和销毁:在代码中创建了多个临时对象,可以考虑使用局部变量或引用来代替,以减少不必要的对象创建和销毁。 以下是优化后的代码示例: ```cpp void PIN_FAST_ANALYSIS_CALL onWrite(THREADID threadid, ADDRINT memoryAddr) { ThreadData* t = get_tls(threadid); t->writeCounter++; bool ch = updateReadVectors(threadid, memoryAddr); auto iit = t->shadowRead.find(memoryAddr); if (iit != t->shadowRead.end() && ch) { traceFileReadWrites << "0x" << std::hex << memoryAddr << "-" << std::dec; for (auto vi = iit->second.first.begin(); vi != iit->second.first.end(); ++vi) { traceFileReadWrites << *vi << ","; } traceFileReadWrites << threadid << "," << t->writeCounter << endl; } PIN_GetLock(&writeLock, threadid + 1); auto it = memoryMap.find(memoryAddr); if (it != memoryMap.end()) { it->second.first.push_back({threadid, t->writeCounter}); if (it->second.second) { it->second.second = (t->tid == it->second.first.back().first); } } else { std::vector<std::pair<THREADID, UINT32>> temp; temp.push_back({threadid, t->writeCounter}); memoryMap[memoryAddr] = {temp, true}; } PIN_ReleaseLock(&writeLock); } ``` 在上述代码中,我将无效的查找操作减少到最小,并使用迭代器遍历容器元素。此外,还可以根据具体需求进行进一步的优化和调整,例如使用更高效的数据结构来代替 `unordered_map`。请确保对共享数据的访问是线程安全的,并避免出现数据竞争和死锁等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值