coding monster
coding monster

Reputation: 394

Is it necessary to lock the reading object?

I'm writing a program which has a shared "queue" of string:

One of the writing threads pushes back the string very frequently. (The string is a log, in fact, which is generated 5 - 10 lines per sec.)

I append following code snipet about explanation above.

class Logger {
    std::mutex m_mutex;
    std::list<std::string> m_queLogs;
public:

    int info(std::string zLog) {
        std::lock_guard<std::mutex> lk(m_mutex);

        m_queLogs.push_back(std::move(zLog));
        ...
    }

    std::string popLog() { //!!!!! Do I need to add a lock_guard here?
        if (m_queLogs.size() == 0)
            return "";

        auto zLog = m_queLogs.front();
        m_queLogs.pop_front();

        return zLog;
    }
}

// Thread 1
int TcpComm::OnRecv(int opCode, char* buf) {

    switch (opCode) {
    case CODE_LOG:                      // generated nearly Real-time 
        Logger::instance()->info(buf);

        break;
        ...
    }
    ...
}

// Thread 2
void MonitorThread(LPVOID lpvoid) {
    while (1) {
        Sleep(60 * 1000);               // generated some times.

        Logger::instance()->info(" ---- monitor signal --- ");
        ...
    }
}


// UI Thread
void CLogView::OnTimer(UINT_PTR nIDEvent)
{
    // every 500 milisecond.
    auto zLog = Logger::instance()->popLog();
    CString strLog = convert_utf8_to_cstring(zLog);

    m_ctrLogView.AppendString(strLog);
}

The strings of m_queLogs are never be removed, only pushed back in writing threads.
Only UI thread pops the log from the m_queLogs.

I think there is no problem without locking in Logger::popLog(), but not sure in case the logging frequency increases.

Please help me to make a decision.

Upvotes: 0

Views: 676

Answers (1)

eerorika
eerorika

Reputation: 238341

Yes. Reader has to lock in order to avoid writes that are unsequenced in relation to the read which would lead to undefined behaviour.

There may be benefit in looking into non-blocking queue data structure. Multiple writers have to lock I think, but reader can be made wait free. But keep in mind that wait free doesn't necessarily imply efficient.

Upvotes: 1

Related Questions