我正在制作自己的通道实现,但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) 不知道如何处理这里的借用检查器。
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) 我正在使用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) 我有一个返回的流程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]]]
有人可以帮忙解决这个问题吗?
我试图使用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 …
我想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) 我使用以下方法使用异步库:
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)
哪个我不明白?
我试图总结我的周围锈期货的头,但我这个代码是应该发送到达的消息弄得rx到sink:
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) 我有检查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) 我是很新,Scala和我想知道是否有某种方式来创建一个虚拟的Future对象来模拟isCompleted来false.我需要这个用于测试目的.
目前我正在使用的是一个假人Future[Int]是这样的:
Future({
while (true) {}
1
})
Run Code Online (Sandbox Code Playgroud)
这非常难看.
编辑
我有object一个变量x是一个Option[Future[Int]].在同一个object我有检查是否x不同的方法,None如果是它检查是否完成.如果未来尚未完成,则可以避免在外部辅助对象上调用方法.测试期间这个外部辅助对象被模拟,我正在检查它是否被调用.为了实现这一点,我目前将x变量设置为Future上面所写的.