简体   繁体   中英

Is it necessary to lock the reading object?

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

  • 2 or 3 threads push back to the queue
  • UI thread pop the string from the queue every 0.5 - 1 seconds. (UI thread means CWnd::OnTimer)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM