coroutine matched with go routine
cnmade opened this issue · 6 comments
I am not ok , i can not find the solution matched with golang go routine.
for example code
func MyQtaskHandler() {
//execute a very long time heavy job in a go routine
go heavyJob();
// but still can return as fast as we can
return json;
}
For this example, user request the api, then quickly got the answer. it's a json return.
and the background go rountine , running a heavy job, which may talk serval hours.
but no matter how long it takes. user don't feel it.
this is golang's magic.
I can not sure how to do it with Rust.
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())
}
curl http://localhost:8080/orders/shoes -d '{"name":"dog", "legs": 4}' -X POST
@goldwind-ting by the document said:
Spawns a new asynchronous task, returning a [JoinHandle](https://docs.rs/tokio/0.2.4/tokio/task/struct.JoinHandle.html) for it.
Spawning a task enables the task to execute concurrently to other tasks. The spawned task may execute on the current thread, or it may be sent to a different thread to be executed. The specifics depend on the current [Runtime](https://docs.rs/tokio/0.2.4/tokio/runtime/struct.Runtime.html) configuration.
There is no guarantee that a spawned task will execute to completion. When a runtime is shutdown, all outstanding tasks are dropped, regardless of the lifecycle of that task.
Looks like it will be dropped, not guarantee to complete .
but i tested go rountine, it will complete, even when the parent invoker thread closed.
@goldwind-ting i don't tell, but golang using large code to implement their goroutine logic.
https://github.com/golang/go/blob/master/src/runtime/runtime2.go
https://github.com/golang/go/blob/master/src/runtime/proc.go#L145
Golang has a main goroutine thread
Have you checked above code?
If you run the code, the spawned task will run until the main
is shutdown.
@goldwind-ting I run it already. but i still can not quite sure the logic behind the action. thanks for explain.