C ++ 17 std :: async非阻塞执行

编程入门 行业动态 更新时间:2024-10-18 20:31:48
本文介绍了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非阻塞执行

本文发布于:2023-11-29 20:23:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647529.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:std   async

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!