当`std :: lock_guard< std :: mutex>`对象没有名称时的不同行为 [英] Different behavior when `std::lock_guard<std::mutex>` object has no name

查看:73
本文介绍了当`std :: lock_guard< std :: mutex>`对象没有名称时的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 std :: mutex std :: thread ,而我对下面2条代码的不同行为感到惊讶:

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;
}

输出是顺序的.但是,如果我不命名变量 std :: lock_guard< std :: mutex> ,则输出为无序

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;
}

在第二种情况下,似乎 std :: lock_guard 没用,为什么?

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

推荐答案

此声明

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.

此CppCon演讲(从

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.

这篇关于当`std :: lock_guard&lt; std :: mutex&gt;`对象没有名称时的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆