标签: future

每次调用 Future::poll 时都需要注册一个新的唤醒器吗?

我正在制作自己的通道实现,但std::task::Context没有明确唤醒器是如何生成的。

我的假代码:

struct MyAtomicWaker {
    lock: SpinLock,
    is_waked: AtomicBool,
    waker: std::task::Waker, 
}

struct WeakAtomicWaker (Weak<MyAtomicWaker>)

impl MyAtomicWaker {
    fn is_waked(&self) -> bool {}
    fn weak(self: Arc<MyAtomicWaker>) -> WeakAtomicWaker;
    fn cancel(&self) {}  // nullify WeakAtomicWaker, means the waker is not waked by a future
}

impl WeakAtomicWaker {
    fn wake(self) {}  // upgrade to arc and can wake only once when waker not cancelled
}

struct ReceiveFuture<T> {
    waker: Option<Arc<MyAtomicWaker>>,
}

impl<T> Drop for ReceiveFuture<T> {
    fn drop(&mut self) …
Run Code Online (Sandbox Code Playgroud)

future rust async-await rust-tokio

1
推荐指数
1
解决办法
2220
查看次数

如何使用 Tokio oneshot 发送器和接收器执行具有内循环的不同任务?

不知道如何处理这里的借用检查器。

use tokio::sync::oneshot; // 1.0.2

fn main() {
    let (sender, receiver) = oneshot::channel::<u8>();
    tokio::spawn(async move {
        loop {
            sender.send(3).unwrap();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

创建此错误:

error[E0382]: use of moved value: `sender`
 --> src/main.rs:7:13
  |
7 |             sender.send(3).unwrap();
  |             ^^^^^^ value moved here, in previous iteration of loop
  |
  = note: move occurs because `sender` has type `tokio::sync::oneshot::Sender<u8>`, which does not implement the `Copy` trait
Run Code Online (Sandbox Code Playgroud)

future rust rust-tokio

1
推荐指数
1
解决办法
5726
查看次数

如何将 Future&lt;bool&gt; 中的“bool”值获取到字段变量中以供以后使用

我正在使用flutter_blue蓝牙服务的包。我想检查设备是否具有蓝牙功能。方法isAvailable好像可以。但是,它返回一个 Future<bool>,我试图将其放入变量中,如下所示:

import 'package:flutter_blue/flutter_blue.dart';

class BT_Base {

final FlutterBlue _fb = FlutterBlue.instance;
bool BTAvailable = true;     // as a default placeholder

BT_Base () {
    BTAvailable = _fixAvail();
}

_fixAvail () async {
  return await _fb.isAvailable;
}

...
Run Code Online (Sandbox Code Playgroud)

我尝试从中获取未来价值并将其存储到BTAvailable. 随后,我使用固定BTAvailable字段来获取要传递到的适当的 Widget,如下所示:

class BTDevicePrompt extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    BT_Base bt = BT_Base();
    var btDeviceRes = bt.scan();

    if(!bt.BTAvailable) return Text('Bluetooth unavailable on device...');
    else if (btDeviceRes.isEmpty) return Text('No Bluetooth devices in …
Run Code Online (Sandbox Code Playgroud)

future dart flutter flutter-futurebuilder

1
推荐指数
1
解决办法
3567
查看次数

从 List[Future[List[String]]] Scala 获取 List[String] 或 Future[List[String]] 的最佳方法

我有一个返回的流程List[Future[List[String]]],我想将其转换为List[String]. 这就是我目前正在做的事情来实现它 -

val functionReturnedValue: List[Future[List[String]]] = functionThatReturnsListOfFutureList()

val listBuffer = new ListBuffer[String]

functionReturnedValue.map{futureList =>
      val list = Await.result(futureList, Duration(10, "seconds"))
      list.map(string => listBuffer += string)
    }

listBuffer.toList
Run Code Online (Sandbox Code Playgroud)

在循环内等待不好,还需要避免使用ListBuffer。

或者,如果可以Future[List[String]]List[Future[List[String]]]

有人可以帮忙解决这个问题吗?

scala future

1
推荐指数
1
解决办法
78
查看次数

使用Play Framework的Akka未来

我试图使用Akka future与play框架连接到远程akka系统.在运行系统之后,akka未来会给我一个警告,即剩下一个参数.

代码如下:

这是[lay lay code:p

ackage controllers;

import com.typesafe.config.ConfigFactory;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import play.*;
import play.mvc.*;

import views.html.*;

public class Application extends Controller {



  public static Result index() throws InterruptedException { 

      System.out.println(" Local Node Called0");


      ActorSystem csystem = ActorSystem.create("Application", ConfigFactory.load().getConfig("LocalNode"));
      ActorRef localNode = csystem.actorOf(new Props(LocalNode.class));

        System.out.println(" Local Node Called1");
        localNode.tell("Hello");
        System.out.println(" Local Node Called2");

        Thread.sleep(5000);
        csystem.shutdown();
        return ok(index.render("I am OK"));
  }           
}
Run Code Online (Sandbox Code Playgroud)

这是play框架本地actor节点

包控制器;

import akka.actor.; import akka.dispatch.Await; import akka.dispatch.Future; import akka.event.Logging; import akka.event.LoggingAdapter; import …

java future akka playframework-2.0

0
推荐指数
1
解决办法
2513
查看次数

如何提供命名函数来映射没有lambdas

我想Future通过使用较少的lambda 来使我的用法更具建设性.目前我正在使用map和lambdas来访问期货的结果.例如:

val rateQuote = future {
  connection.getCurrentValue(USD)
}
val purchase = rateQuote map { quote =>  
  if (isProfitable(quote)) connection.buy(amount, quote)
  else throw new Exception("not profitable")
}
purchase onSuccess {
  case _ => println("Purchased " + amount + " USD")
}
Run Code Online (Sandbox Code Playgroud)

map我不想为每个提供lambda(匿名函数),而是提供一个命名函数/方法.我该怎么办?例如:

val rateQuote = future {
  connection.getCurrentValue(USD)
}
def namedFunction(arg: Arg) = 
  if (isProfitable(quote)) connection.buy(amount, quote)
  else throw new Exception("not profitable")

val purchase = rateQuote map { quote => namedFunction }
Run Code Online (Sandbox Code Playgroud)

甚至更好

val purchase = rateQuote …
Run Code Online (Sandbox Code Playgroud)

lambda scala future anonymous-function

0
推荐指数
1
解决办法
104
查看次数

Scala方法返回Future

我使用以下方法使用异步库:

def myMethod(param: Long, isTru: Boolean): Future[Option[MyType]] = async {

  if (isTru) {
    val promise = Promise[Option[MyType]]

    val myFuture = doSomething(param)

    myFuture.onComplete {
      case Success(succ) => {
        promise.success(Some(MyType(param, succ)))
      }
      case Failure(fail) => promise.failure(fail)
    }

    promise.future // fails here
  }
  else {
    None
  }
}
Run Code Online (Sandbox Code Playgroud)

它无法编译错误:

[error] found: scala.concurrent.Future[Option[MyType]]
[error] required: Option[MyType]
Run Code Online (Sandbox Code Playgroud)

哪个我不明白?

scala future promise

0
推荐指数
1
解决办法
772
查看次数

在将消息从期货渠道转发到WebSocket接收器时,类型不匹配解决错误类型

我试图总结我的周围锈期货的头,但我这个代码是应该发送到达的消息弄得rxsink:

extern crate futures;
extern crate tokio_core;
extern crate websocket;

use websocket::message::OwnedMessage;
use websocket::server::InvalidConnection;
use websocket::async::Server;

use tokio_core::reactor::Core;
use futures::{Future, Sink, Stream};
use futures::sync::mpsc;
use std::{thread, time};
use futures::sync::mpsc::Receiver;

fn main() {
    let mut core = Core::new().unwrap();
    let (mut tx, rx) = mpsc::channel(5);
    thread::spawn(|| worker(rx));
    let mut i = 0;
    loop {
        let res = tx.clone().send(OwnedMessage::Text(format!("Test {}", i)));
        core.run(res);
        i += 1;
        let period = time::Duration::from_millis(200);
        thread::sleep(period);
    }
}

fn worker(rx: Receiver<OwnedMessage>) {
    let mut core …
Run Code Online (Sandbox Code Playgroud)

future rust rust-tokio

0
推荐指数
1
解决办法
1066
查看次数

如何杀死CompletableFuture相关的主题?

我有检查CompletableFuture执行时间的方法.如果此类CompletableFuture执行的时间超过2秒,我想要终止此任务.但是,如果我没有执行CompletableFuture方法的控制线程,我该怎么办呢?

       final CompletableFuture<List<List<Student>>> responseFuture = new CompletableFuture<>();
responseFuture.supplyAsync(this::createAllRandomGroups)
        .thenAccept(this::printGroups)
        .exceptionally(throwable -> {
            throwable.printStackTrace();
            return null;
        });
Run Code Online (Sandbox Code Playgroud)

createAllRandomGroups()

private List<List<Student>> createAllRandomGroups() {
    System.out.println("XD");
    List<Student> allStudents = ClassGroupUtils.getActiveUsers();
    Controller controller = Controller.getInstance();
    List<List<Student>> groups = new ArrayList<>();
    int groupSize = Integer.valueOf(controller.getGroupSizeComboBox().getSelectionModel().getSelectedItem());
    int numberOfGroupsToGenerate = allStudents.size() / groupSize;
    int studentWithoutGroup = allStudents.size() % groupSize;
    if (studentWithoutGroup != 0) groups.add(this.getListOfStudentsWithoutGroup(allStudents, groupSize));
    for(int i = 0; i < numberOfGroupsToGenerate; i++) {
        boolean isGroupCreated = false;
        while (!isGroupCreated){
            Collections.shuffle(allStudents);
            List<Student> newGroup = this.createNewRandomGroupOfStudents(allStudents, groupSize);
            groups.add(newGroup);
            if …
Run Code Online (Sandbox Code Playgroud)

java multithreading future java-8 completable-future

0
推荐指数
1
解决办法
2076
查看次数

Scala dummy未来未完成

我是很新,Scala和我想知道是否有某种方式来创建一个虚拟的Future对象来模拟isCompletedfalse.我需要这个用于测试目的.

目前我正在使用的是一个假人Future[Int]是这样的:

Future({
    while (true) {}
    1
})
Run Code Online (Sandbox Code Playgroud)

这非常难看.

编辑 我有object一个变量x是一个Option[Future[Int]].在同一个object我有检查是否x不同的方法,None如果是它检查是否完成.如果未来尚未完成,则可以避免在外部辅助对象上调用方法.测试期间这个外部辅助对象被模拟,我正在检查它是否被调用.为了实现这一点,我目前将x变量设置为Future上面所写的.

testing scala future

0
推荐指数
1
解决办法
206
查看次数