我试图设计一个包含ofstreams的线程安全的unordered_map。这个实现有效吗?工作线程将锁定写入的流,然后调用解锁函数。
class ThreadSafeStreamMap
{
public:
ThreadSafeStreamMap() :
m_map(),
m_locks()
{}
~ThreadSafeStreamMap() {}
std::ofstream& lockStream(const std::string& instrument, const uint32_t& apid)
{
auto& mut = getMutex(apid);
mut.lock();
auto& stream = getStream(apid);
if (stream.is_open())
{
return stream;
}
else
{
stream.open("output/" + instrument + "_" + std::to_string(apid) + ".txt", std::ios::ate);
return stream;
}
}
void unlockStream(const uint32_t& apid)
{
auto& mut = getMutex(apid);
mut.unlock();
}
std::mutex& getMutex(const uint32_t& apid)
{
return m_locks[apid];
}
std::ofstream& getStream(const uint32_t& apid)
{
return m_map[apid];
}
private:
std::unordered_map<uint32_t, std::ofstream> m_map;
std::unordered_map<uint32_t, std::mutex> m_locks;
};