0

I wish to resolve the following code, but Rust panics because the actix future server() does not implement the trait Send. I didn't find a way to paralelize the actix server whithout error.

use tokio::runtime::Runtime;
use actix_web::{get, App, HttpResponse, HttpServer, Responder};

fn main() {
    let rt = Runtime::new().unwrap();
    let handle = rt.spawn(server());
    rt.block_on(handle).unwrap();

    // other activities in paralell with the server, is a crypto bot
    // and the server is for view the behavior
}

#[get("/")]
async fn hello_world() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

async fn server() -> Result<(), std::io::Error> {
    HttpServer::new(|| {
        App::new().service(hello_world)
    })
    .bind(("127.0.0.1", 5000))?
    .run()
    .await
}

the relevant panic info is the following:

error: future cannot be sent between threads safely
   --> src/main.rs:7:27
    |
7   |     let handle = rt.spawn(server());
    |                           ^^^^^^^^ future returned by `server` is not `Send`
    |
    = help: within `impl std::future::Future<Output = Result<(), std::io::Error>>`, the trait `Send` is not implemented for `Rc<[Box<dyn Fn() -> Pin<Box<dyn Future<Output = ...>>>>]>`
note: future is not `Send` as this value is used across an await

1 Answer 1

0

Use actix_web::rt::spawn(), which does not have a Send requirement, and runs the future on the current thread:

https://docs.rs/actix-web/latest/actix_web/rt/fn.spawn.html

Any other Send futures or tasks can be spawned into different threads, and any other non-Send (!Send) futures can be spawned on the same thread, they will cooperate to share execution time.

If you need a dedicated thread for a !Send future, you can create it manually using std::thread::Builder, then use Handle::block_on() to call actix_web::rt::spawn() to run the future locally on that thread.

Here is a similar answer that covers most of that:

https://stackoverflow.com/a/75387575/4970342

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.