Search code examples
c++lockingthread-synchronization

RAII Locking with std::lock_guard<std::mutex>(m_mutex); instead of std::lock_guard<std::mutex> lk(m_mutex);


It's probably a stupid question, but I discovered a few occurences of a lock_guard without variable.

void func() {
  std::lock_guard<std::mutex>(m_mutex);
  m_value = "2";
}

Instead of the following with lk variable.

void func() {
  std::lock_guard<std::mutex> lk(m_mutex);
  m_value = "2";
}

The first version is probably bullshit and causes the access to be in some kind of soft sync mode, since the lock is held for a short moment, so no longer running function holds the lock currently, right?

Or did I learn something here and lk variable is actually not required?


Solution

  • The following code shows you why it is wrong :

    #include <iostream>
    
    struct raii_class
    {
        raii_class()
        {
            std::cout << "raii construct\n";
        }
        ~raii_class()
        {
            std::cout << "raii destruct\n";
        }
    };
    
    int main()
    {
        raii_class{};
        std::cout << "body\n";
        return 0;
    }
    

    Outputs :

    raii construct
    raii destruct
    body