Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How does Corece handle CPU-bound operations? #35

Open
lucasmsoares96 opened this issue Nov 11, 2023 · 2 comments
Open

How does Corece handle CPU-bound operations? #35

lucasmsoares96 opened this issue Nov 11, 2023 · 2 comments

Comments

@lucasmsoares96
Copy link

I am migrating my project from actix to coerce and I have a question about how CPU-bound tasks are managed. The example below shows the actix code to perform the fibonacci operation on 3 Arbiters. An arbiter is a single-threaded event loop that runs one or more actors. In this way, although the event loop is blocked by the fibonacci calculation, it is possible to perform 3 calculations in parallel.

#[actix::main]
async fn main() {
    let start = Instant::now();
    let a1 = Arbiter::new().handle();
    let a2 = Arbiter::new().handle();
    let a3 = Arbiter::new().handle();

    let addr1 = Calculator::start_in_arbiter(&a1, |_ctx| Calculator);
    let addr2 = Calculator::start_in_arbiter(&a2, |_ctx| Calculator);
    let addr3 = Calculator::start_in_arbiter(&a3, |_ctx| Calculator);

    let fib_future1 = addr1.send(Fibonacci(43));
    let fib_future2 = addr2.send(Fibonacci(43));
    let fib_future3 = addr3.send(Fibonacci(43));

    let futures = vec![fib_future1, fib_future2, fib_future3];

    let results = join_all(futures).await;

    for (i, result) in results.iter().enumerate() {
        match result {
            Ok(value) => println!("Resultado {}: {}", i + 1, value),
            Err(e) => println!("Erro ao receber o resultado {}: {:?}", i + 1, e),
        }
    }

    let duration = start.elapsed();
    println!("Tempo decorrido: {:?}", duration);
}

How does Coerce work under the hood? I couldn't find anything about it in the documentation. How to perform 3 CPU-bound tasks in parallel as in the example?

@LeonHartley
Copy link
Owner

Hey @lucasmsoares96!

Coerce uses the tokio runtime under the hood. For CPU-intensive work I would most likely dispatch that work to a separate thread pool and notify the actor when the work is complete.

For this I would recommend using a library like Rayon, which offers a work-stealing thread pool:
https://crates.io/crates/rayon

I can give you some examples on how you could achieve this with Coerce, if you'd like?

Leon

@lucasmsoares96
Copy link
Author

An example of this will help a lot! Thank you very much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants