Lambda内循环 [英] Lambda inside loop

查看:139
本文介绍了Lambda内循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个lambda在一个for循环与循环变量参数在lambda。当我运行它,我期望输出数字0-9。

I have a lambda inside a for loop with the loop variable parameter in the lambda. When I run it, I expect the numbers 0-9 to be output. But since it is a lambda, the x doesn't get evaluated immediately.

    for( int x = 0; x < n; ++x)
    {
            vec.push_back(thread{[&x](){
                    m.lock();
                    cout << x << endl;
                    m.unlock();
            }});
    }

输出:

0
3
3
9

等。

其他语言的解决方案是创建一个临时变量,

The solution for other languages would be to create a temporary variable,

    for( int x = 0; x < n; ++x)
    {
            int tmp = x;
            vec.push_back(thread{[&tmp](){
                    m.lock();
                    cout << tmp << endl;
                    m.unlock();
            }});
    }

但似乎无效。

请参阅主题接收错误的参数

奖金:

在我搜索答案时,我偶然发现了这个问题
通用C ++ 11 Threads类使用lambda
建议不要使用容器这将使迭代器无效。为什么会是/

In my search for an answer, I stumbled upon this question Generalizing C++11 Threads class to work with lambda which recommends not using a container that would invalidate the iterators. Why would that be/

推荐答案

指定捕获时,可以通过值捕获和通过引用捕获。您已选择通过引用捕获。通过引用捕获意味着lambda函数内的变量引用同一个对象。这意味着对该变量的任何更改都将被共享,并且还需要确保引用对象在lambda函数的生命周期内停留。

When you specify the capture, you can choose between capture by value and capture by reference. You have chosen to capture by reference. Capturing by reference means that the variable inside the lambda function is referring to the same object. The implication is that any changes to this variable will be shared and you also need to make sure that the referenced object stays around for the life-time of the lambda function.

你可能想要通过值捕获。为此,您可以将捕获规范替换为 [=] 或变为 [x] 。后者确保只有 x 可以访问,而前者允许访问其他变量。

You probably meant to capture by values. To do this, you can either replace the capture specification to become [=] or to become [x]. The latter makes sure that only x can be accessed while the former would allow other variables to be accessible.

BTW ,我建议明确使用 lock() unlock() 使用其中一个锁定防护。这样,你的循环体就像这样:

BTW, I'd recommend not using lock() and unlock() explicitly but rather use one of the lock guards. With this, the body of your loop would look something like this:

vec.push_back(std::thread{[x](){
    std::lock_guard<std::mutex> kerberos(m);
    std::cout << x << "\n";
}});

这篇关于Lambda内循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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