future

std future使用(简单)

匿名 (未验证) 提交于 2019-12-02 22:56:40
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/river472242652/article/details/82965264 #include <iostream> #include <vector> #include <thread> #include <functional> #include <atomic> #include <mutex> #include <future> /** *std future作用 1取回另一个线程计算结果 可以将future /promise当成线程间传递结果的通信信道 std::packaged_task();自动将一个future与promise联系在一起 2防止线程中出现异常后终止整个程序(线程本身处理异常) *Date :[10/8/2018 ] *Author :[RS] */ int calculate() { std::this_thread::sleep_for(std::chrono::seconds(5)); std::cout << "异步中" << std::endl; return 123; } int main() { auto fut = std::async(calculate); std::cout << "非异步" << std::endl; int

Scala Future with filter in for comprehension

橙三吉。 提交于 2019-12-02 22:12:52
In the example below I get the exception java.util.NoSuchElementException: Future.filter predicate is not satisfied I want to have the result Future( Test2 ) when the check if( i == 2 ) fails. How do I handle filter/if within a for comprehension that deals with composing futures? Below is a simplified example that works in the Scala REPL. Code: import scala.concurrent.Future import scala.util.{ Try, Success, Failure } import scala.concurrent.ExecutionContext.Implicits.global val f1 = Future( 1 ) val f2 = for { i <- f1 if( i == 2 ) } yield "Test1" f2.recover{ case _ => "Test2" } f2.value tgr In

ListenableFuture to scala Future

左心房为你撑大大i 提交于 2019-12-02 21:56:27
I am in the process of writing a small scala wrapper around a java library. The java library has an object QueryExecutor exposing 2 methods: execute(query): Result asyncExecute(query): ListenableFuture[Result] ListenableFuture in this context is the one from the guava library. I want my scala wrapper to return a Future[Result] instead of the java object, but I am not sure what is the best way to implement that. Here are 2 solutions I came up with: future { executor.execute(query) } and val p = promise[Result] val guavaFuture = executor.asyncExecute(query) Futures.addCallback(guavaFuture, new

How to use take_while with futures::Stream?

∥☆過路亽.° 提交于 2019-12-02 20:57:27
问题 I'm trying to understand what syntax should I use for take_while() with futures::Stream; crate (0.1.25). Here's a piece of code (on playground): use futures::{stream, Stream}; // 0.1.25 fn into_many(i: i32) -> impl Stream<Item = i32, Error = ()> { stream::iter_ok(0..i) } fn main() { println!("start:"); let _ = into_many(10) // .take_while(|x| { x < 10 }) .map(|x| { println!("number={}", x); x }) .wait(); for _ in foo {} // ← this (by @mcarton) println!("finish:"); } The main goal is to

How to resolve a list of futures in Scala

五迷三道 提交于 2019-12-02 20:28:57
I have a call that returns a Future. However, I need to make n calls so I will get back n futures. I am wondering how I would get the futures to all resolve before proceeding (without blocking the server) For example, while(counter < numCalls){ val future = call(counter) future.map{ x => //do stuff } counter += 1 } //Now I want to execute code here after ALL the futures are resolved without //blocking the server You can use Future.sequence(futureList) to convert a List[Future[X]] to a Future[List[X]] . And since the latter is just a simple Future , you can wait for it to finish with the help

How to combine Futures of different types into a single Future without using zip()

牧云@^-^@ 提交于 2019-12-02 17:05:31
I want to create a Future of type Future[(Class1,Class2,Class3)] from below code. However the only way I have found to do this is by using zip(). I find the solution ugly and properly not optimal. Can anybody enlightened me. val v = for ( a <- { val f0:Future[Class1] = process1 val f1:Future[Class2] = process2 val f2:Future[Class3] = process3 f0.zip(f1).zip(f2).map(x => (x._1._1,x._1._2,x._2)) } yield a // Future[(Class1,Class2,Class3)] I have also tried to use Future.sequence(List(f0, f1, f2)) but this will not work as the new Future will have type of Future[List[U]] where U is the lub of

Get rid of Scala Future nesting

限于喜欢 提交于 2019-12-02 15:55:24
Again and again I am struggling when a function relies on some future results. This usually boils down to a result like Future[Seq[Future[MyObject]]] To get rid of that I now use Await inside a helper function to get a non-future object out and reduce the nesting. It looks like this def findAll(page: Int, perPage: Int): Future[Seq[Idea]] = { val ideas: Future[Seq[Idea]] = collection.find(Json.obj()) // [...] ideas.map(_.map { // UGLY? idea => { // THIS RETURNED A Future[JsObject] before val shortInfo: JsObject = UserDao.getShortInfo(idea.user_id) idea.copy(user_data = Some(shortInfo)) } }) }

Callable和Future学习笔记

大城市里の小女人 提交于 2019-12-02 14:36:52
一。 1>Callable和Future接口介绍 Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可以被创建为线程的来执行的类。 2>Callable和Runnable比较 1. Callable规定的方法是call,Runnable规定的方法是run 2. callable的任务执行后可以返回值,Runnable的run是无返回值的 3.call方法可以抛出异常,run方法不能抛出异常。我们可以根据call方法是否抛出异常进行不同操作(因为try-catch不应该作为控制流程的条件,所以不推荐这样做); 4.运行callable任务可拿到一个Future对象,Future表示的是异步计算结果,它提供了检查计算是否完成的方法和等待计算完成检索计算结果的方法。通过Future对象可以了解任务的执行情况,可以取消任务的执行,还可以获取任务执行的结果。 3>Future中的方法介绍 1.future.get()将等待callable线程执行返回结果。future.get(timeout, unit)如果等待超时将抛出超时异常。 2.future.cancel(boolean)将试图终端当前线程, boolean作用带研究 例子测试,代码如下,注意被注掉的两个地方,可以去掉注释运行试试 public class

Java终结任务:Callable和Future

佐手、 提交于 2019-12-02 14:36:37
在这里首先介绍下Callable和Future,我们知道通常创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口,但是这两种方式创建的线程不返回结果,而Callable是和Runnable类似的接口定义,但是通过实现Callable接口创建的线程可以有返回值,返回值类型可以任意定义。 Callable接口 public interface Callable<V> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception; } 可以看到,这是一个泛型接口,call()函数返回的类型就是传递进来的V类型。 那么怎么使用Callable呢?一般情况下是配合ExecutorService来使用的,在ExecutorService接口中声明了若干个submit方法的重载版本: <T> Future<T> submit(Callable<T> task); <T> Future<T> submit(Runnable task, T result); Future<?>

Callable和Future

我是研究僧i 提交于 2019-12-02 14:36:26
Callable与 Future 两功能是Java 5版本中加入的,Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类 。 Callable 的接口定义如下: public interface Callable<V> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception; } Callable 和 Runnable 的区别如下: Callable 定义的方法是 call ,而 Runnable 定义的方法是 run 。 Callable 的 call 方法可以有返回值, 而 Runnable 的 run 方法不能有返回值 。 Callable 的 call 方法可抛出异常,而 Runnable 的 run 方法不能抛出异常。 Future 定义 Future 表示异步计算的结果,它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。 Future 的 cancel 方法可以取消任务的执行,它有一布尔参数,参数为 true