lundi 3 juillet 2017

Thread Safe ofstream access

I'm attempting to design a thread-safe unordered_map containing ofstreams. Is this implementation valid? Worker threads will lock the streams write to it, and then call the unlock function.

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;
};

Aucun commentaire:

Enregistrer un commentaire