静态内联关联集合通常指的是在C++中,使用static inline
关键字定义的关联集合(如std::map
、std::unordered_map
等)。静态内联变量在每个编译单元(通常是每个源文件)中都有一个实例,但在链接时只会保留一个实例。
读访问冲突(Read Access Violation)通常发生在多线程环境中,当一个线程试图读取另一个线程正在修改的数据时,可能会导致数据不一致或程序崩溃。
std::map
和std::unordered_map
,适用于需要快速查找、插入和删除的场景。#include <gtest/gtest.h>
#include <map>
#include <mutex>
static inline std::map<int, int> sharedMap;
static inline std::mutex mapMutex;
void insertIntoMap(int key, int value) {
std::lock_guard<std::mutex> lock(mapMutex);
sharedMap[key] = value;
}
int getFromMap(int key) {
std::lock_guard<std::mutex> lock(mapMutex);
if (sharedMap.find(key) != sharedMap.end()) {
return sharedMap[key];
}
return -1; // 或者抛出异常
}
#include <gtest/gtest.h>
#include <map>
class SharedMap {
public:
static SharedMap& getInstance() {
static SharedMap instance;
return instance;
}
void insert(int key, int value) {
map_[key] = value;
}
int get(int key) {
if (map_.find(key) != map_.end()) {
return map_[key];
}
return -1; // 或者抛出异常
}
private:
SharedMap() {}
std::map<int, int> map_;
};
TEST(SharedMapTest, InsertAndGet) {
SharedMap::getInstance().insert(1, 100);
EXPECT_EQ(SharedMap::getInstance().get(1), 100);
}
#include <gtest/gtest.h>
#include <map>
static inline thread_local std::map<int, int> threadLocalMap;
void insertIntoThreadLocalMap(int key, int value) {
threadLocalMap[key] = value;
}
int getFromThreadLocalMap(int key) {
if (threadLocalMap.find(key) != threadLocalMap.end()) {
return threadLocalMap[key];
}
return -1; // 或者抛出异常
}
读访问冲突通常是由于多线程环境下对共享数据的并发访问引起的。通过使用互斥锁、单例模式或线程局部存储,可以有效避免这类问题。选择合适的解决方案取决于具体的应用场景和需求。
领取专属 10元无门槛券
手把手带您无忧上云