Sobes.tech
Junior — Senior

Code analysis and evaluation using mutex

livecode

Task condition

It is necessary to carefully analyze the provided C++ example and identify potential issues related to synchronization using std::mutex and std::lock_guard. Pay attention to how the cerr_mutex mutex is locked in the functions foo and bar, and assess whether there is a risk of deadlock when calling bar() from foo(). If deficiencies are found, suggest correct ways to fix them.

# include <iostream>
# include <mutex>

std::mutex cerr_mutex;

int bar()
{
    std::lock_guard<std::mutex> lock(cerr_mutex);
    std::cerr << "bar" << std::endl;

    return 42;
}

void foo()
{
    std::lock_guard<std::mutex> lock(cerr_mutex);
    std::cerr << "foo, bar - " << bar() << std::endl;
}

int main(int argc, char* argv[])
{
    foo();

    return 0;
}