不同编程语言中的协程库

Golang

golang中的go func 最简单

func HelloHttpHandle() {
   //execute a background job, like send notify to user, via sms or email.
    go func();
  // the request will complete soon, return json to user http client
   return json;
}

Rust

参见

https://github.com/async-rs/async-std/issues/1032

use tide::Request;
use tide::prelude::*;
use async_std::task;

#[derive(Debug, Deserialize)]
struct Animal {
    name: String,
    legs: u16,
}

#[async_std::main]
async fn main() -> tide::Result<()> {
    let mut app = tide::new();
    app.at("/orders/shoes").post(order_shoes);
    app.listen("127.0.0.1:8080").await?;
    Ok(())
}

async fn coroutine(){
    task::sleep(std::time::Duration::from_secs(2)).await;
    println!("woken!");
}

async fn order_shoes(mut req: Request<()>) -> tide::Result {
    let Animal { name, legs } = req.body_json().await?;
    task::spawn(coroutine());
    Ok(format!("Hello, {}! I've put in an order for {} shoes", name, legs).into())
}

 

Scala

 

Dart

参见

https://github.com/dart-lang/sdk/issues/49403

 

Future<T> runInIsolate(FutureOr<T> computation()) {
  var resultPort = ReceivePort();
  return Future.wait([
     resultPort.first,
     Isolate.spawn((SendPort result) async => result.send(await computation()), resultPort.sendPort)
  ]).then((pair) => pair[0] as T)..ignore();
} 

  var delayedResult = runInIsolate(someComputation);
  print("continue immediately after");
  ...
  /// eventually
  var result = await delayedResult; // when you really need the result.

分类: 默认 标签: 发布于: 2022-07-07 10:17:37, 更新于: 2022-07-08 16:42:56