C ++ 17 std :: async非阻塞执行 [英] C++17 std::async non blocking execution

查看:147
本文介绍了C ++ 17 std :: async非阻塞执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了这个C ++ 17代码来模仿我需要的东西.

I have created this C++17 code that mimics something that I need.

std::cout << "start" << std::endl;

auto a = std::async([]() -> int {
    std::this_thread::sleep_for(std::chrono::seconds{ 5 });
    return 2;
});
std::cout << a.get() << std::endl;

std::cout << "stop" << std::endl;

线程在这里睡觉,但在实际示例中,我进行了大量操作,并且返回了可以为0、1或7的整数.这是我的输出:

The thread sleeps here but in real example I do heavy operations and I return an integer which can be 0, 1 or 7. This is my output:

start
2
stop

这很好!此代码不会冻结我的UI.我知道 a.get()是一种阻止操作,但是有没有一种可以阻止的方法?

This is good! This code will not freeze my UI. I know that a.get() is a blocking operation but is there a way to be non blocking?

换句话说:代替

start
2
stop

我能否得到输出

start
stop
2

使用 async ?我需要异步,因为我在线发现了需要返回值时非常有用.这也很容易阅读!我不想使用 std :: packaged_task ,promise,future等,因为 async 很容易.

using async? I need async because I have found online that it is useful when return a value is needed. It is also easy to read! I do not want to use std::packaged_task, promises, futures etc because async is easy.

如果不能不阻塞,我还可以使用其他东西吗?

If it cannot be non blocking can I use something else?

推荐答案

此代码将输出您需要的内容:

This code will output what you need:

std::cout << "start" << std::endl;

std::thread{
    []() {
        auto a = std::async([]() -> int {
            std::this_thread::sleep_for(std::chrono::seconds{ 5 });
            return 2;
        });

        std::cout << a.get() << std::endl;
    }
}.detach();

std::cout << "stop" << std::endl;


如果我是你,我根本不会使用 async .如果只需要显示一个值而又不想阻塞,则应该执行其他操作.例如:


If I were you I wouldn't use async at all. If you just need to display a value and you don't want to block, you should do something else. For example:

std::cout << "start" << std::endl;

std::thread{
    []() {
        //do here what you need and print the result
    }
}.detach();

/* ... or ...
auto t = std::thread{ ... };
t.detach();
*/

std::cout << "stop" << std::endl;

看到 detach()使新线程独立"并且在 join()阻塞时不会阻塞.关键是 async 必须阻塞,因为如果必须执行需要大量时间的操作,则必须花费该时间!

See that detach() makes the new thread "independent" and doesn't block while join() blocks. The point is that async must block because if it has to do an operation that takes a lot of time, it has to spend that time!

这篇关于C ++ 17 std :: async非阻塞执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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