Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behavior when `std::lock_guard<std::mutex>` object has no name

I'm learning about std::mutex, std::thread and I am surprised at the different behavior of 2 pieces of code below:

#include <iostream>
#include <mutex>
#include <thread>
using namespace std;

std::mutex mtx;

void foo(int k)
{
    std::lock_guard<std::mutex> lg{ mtx };
    for (int i = 0; i < 10; ++i)
        cout << "This is a test!" << i << endl;
    cout << "The test " << k << " has been finished." << endl;
}

int main()
{
    std::thread t1(foo, 1);
    std::thread t2(foo, 2);
    t1.join();
    t2.join();
    return 0;
}

The output is sequential. But if I donot name variable std::lock_guard<std::mutex>, the output is unordered

void foo(int k)
{
    std::lock_guard<std::mutex> { mtx }; // just erase the name of variable
    for (int i = 0; i < 10; ++i)
        cout << "This is a test!" << i << endl;
    cout << "The test " << k << " has been finished." << endl;
}

It seems like std::lock_guard is no use in 2nd case, Why?

like image 727
rsy56640 Avatar asked Aug 22 '18 08:08

rsy56640


People also ask

What happens when a mutex is given to a lock_guard?

When a lock_guard object is created, it attempts to take ownership of the mutex it is given. When control leaves the scope in which the lock_guard object was created, the lock_guard is destructed and the mutex is released.

What is the behavior of mutex when mutex is destroyed?

The behavior of a program is undefined if a mutexis destroyed while still owned by any threads, or a thread terminates while owning a mutex. The mutexclass satisfies all requirements of Mutexand StandardLayoutType. std::mutexis neither copyable nor movable. Contents 1Member types 2Member functions 2.1Locking 2.2Native handle 3Notes 4Example

How to unlock a mutex in C++?

The programmer is able to unlock the mutex with the help of the guard object This means that the programmer can unlock the mutex before the guard2 ’s life ends. After the mutex was unlocked, the programmer can also lock it again We should mention that the std::unique_lock has also some other member functions.

What is a mutex class in C++?

(since C++11) The mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.


1 Answers

This declaration

std::lock_guard<std::mutex> { mtx };

doesn't bind the created object to a name, it's a temporary variable that exists only for this particular statement. Opposed to that, a variable that has a name and is created on the stack lives until the end of the scope in which it's created.

In this CppCon talk (starting at 31:42), the presenter lists the creation of temporary std::lock_guard instances not bound to a local variable as a common bug in the Facebook code base.

like image 125
lubgr Avatar answered Oct 04 '22 15:10

lubgr