// 缓存已计算的规范化路径 static thread_local std::unordered_map<std::filesystem::path, std::size_t> cache;
时间: 2025-03-08 22:11:46 浏览: 12
使用线程本地存储缓存文件系统路径规范化
为了实现高效的文件系统路径规范化操作,可以利用线程本地存储(Thread Local Storage, TLS)来保存已经计算过的路径结果。这种方式不仅能够提升性能,还能保持良好的可读性和维护性。
下面是一个基于 C++11 及以上标准库的解决方案:
定义必要的头文件和命名空间
#include <string>
#include <unordered_map>
#include <thread>
#include <mutex>
namespace fs {
class PathNormalizer {
static thread_local std::unordered_map<std::string, std::string> cache;
mutable std::recursive_mutex mutex_;
// 私有化默认构造函数防止外部实例化
PathNormalizer() {}
public:
~PathNormalizer() {}
/// @brief 获取单例对象指针
static PathNormalizer* instance();
/// @brief 对给定路径执行标准化处理并返回结果
const char* normalize(const char *path);
};
}
初始化静态成员变量
// 静态初始化器用于创建唯一的全局实例
fs::PathNormalizer* fs::PathNormalizer::instance_ = nullptr;
// 线程局部哈希表用来存储每条线程自己的映射关系
thread_local std::unordered_map<std::string, std::string> fs::PathNormalizer::cache;
实现 normalize
成员方法
const char* fs::PathNormalizer::normalize(const char *raw_path) {
auto normalized_str = raw_path; // 默认情况下不做任何改变
try {
if (std::strlen(raw_path)) {
std::lock_guard<std::recursive_mutex> lock(mutex_);
// 尝试查找缓存中的记录
auto it = cache.find(std::string(raw_path));
if(it != end(cache))
return (*it).second.c_str();
// 如果找不到则重新计算新的规范形式...
// 这里省略具体算法逻辑
// ...并将新值加入到当前线程对应的字典中
cache.emplace_hint(end(cache), std::make_pair(
std::string(raw_path),
/* 计算得到的标准字符串 */ ""
));
// 返回最终的结果
return cache.at(std::string(raw_path)).c_str();
}
} catch (...) {
throw std::runtime_error("Failed to process path normalization");
}
return normalized_str;
}
/// 单例获取接口的具体定义
fs::PathNormalizer* fs::PathNormalizer::instance(){
if (!instance_) {
static fs::PathNormalizer singleton_instance;
instance_=&singleton_instance;
}
return instance_;
}
此方案通过使用 thread_local
关键字确保每个线程都有自己独立的数据副本[^3],从而减少了多线程环境下的竞争条件风险;同时借助于 STL 提供的安全容器类型实现了简单的 LRU 或者 FIFO 缓存机制。当遇到重复请求相同的原始路径时可以直接从对应线程内的高速缓冲区快速检索出预处理后的版本,进而显著降低 I/O 开销与时间复杂度。
相关推荐


















