Sobes.tech
Junior — Senior

Review and improve the message processing function from the shared queue

livecode

Task condition

It is necessary to review the handle_message function, which reads messages from a global queue and passes them for long processing.

  1. Identify logical errors and potential race conditions.
  2. Propose and implement code refactoring.
  3. Pay special attention to the correct use of mutex: proper locking, unlocking, and avoiding double unlocking.
std::queue<std::string> g_messages;

void long_calculation_with_message(const std::string& message);

void handle_message() {
    std::mutex mutex;
    mutex.lock();

    if (!g_messages.empty()) {
        const std::string& message = g_messages.front();
        mutex.unlock();

        long_calculation_with_message(message);

        mutex.lock();
        g_messages.pop();
        mutex.unlock();
    }

    mutex.unlock();
}