微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法使用异步actor

如何解决无法使用异步actor

我正在尝试使用 actix documentation 中记录的演员。但即使是 doc 示例也不适合我。我尝试了以下编译但不打印消息“收到 fibo 消息”的代码

use actix::prelude::*;

// #[derive(Message)]
// #[rtype(Result = "Result<u64,()>")]
// struct Fibonacci(pub u32);

struct Fibonacci(pub u32);
impl Message for Fibonacci {
    type Result = Result<u64,()>;
}

struct SyncActor;

impl Actor for SyncActor {
    // It's important to note that you use "SyncContext" here instead of "Context".
    type Context = SyncContext<Self>;
}

impl Handler<Fibonacci> for SyncActor {
    type Result = Result<u64,()>;

    fn handle(&mut self,msg: Fibonacci,_: &mut Self::Context) -> Self::Result {
        println!("Received fibo message");
        if msg.0 == 0 {
            Err(())
        } else if msg.0 == 1 {
            Ok(1)
        } else {
            let mut i = 0;
            let mut sum = 0;
            let mut last = 0;
            let mut curr = 1;
            while i < msg.0 - 1 {
                sum = last + curr;
                last = curr;
                curr = sum;
                i += 1;
            }
            Ok(sum)
        }
    }
}

fn main() {
    System::new().block_on(async {
        // Start the SyncArbiter with 2 threads,and receive the address of the Actor pool.
        let addr = SyncArbiter::start(2,|| SyncActor);

        // send 5 messages
        for n in 5..10 {
            // As there are 2 threads,there are at least 2 messages always being processed
            // concurrently by the SyncActor.
            println!("Sending fibo message");
            addr.do_send(Fibonacci(n));
        }
    });
}

此程序显示 5 次:

发送 fibo 消息

两点说明,首先我无法使用宏rtype,我使用自己实现Message。然后这行 addr.do_send(Fibonacci(n)) 似乎没有给我的演员发送任何东西。但是,如果我使用 addr.send(Fibonacci(n)).await;,我的消息会在参与者端发送和接收。但由于我正在等待发送函数,它会同步处理消息,而不是使用我理论上定义的 2 个线程。

我也尝试在主循环后使用 thread::sleep 等待,但消息也没有到达。

我可能误解了一些东西,但对我来说似乎很奇怪。

Cargo.toml 文件

[dependencies]
actix = "0.11.1"
actix-rt = "2.2.0"

解决方法

我终于设法让它工作了,虽然我不明白为什么。简单地使用 tokio 等待 ctrl-C 使我可以调用 do_send/try_send 并并行工作。

fn main() {
    System::new().block_on(async {
        // Start the SyncArbiter with 4 threads,and receive the address of the Actor pool.
        let addr = SyncArbiter::start(4,|| SyncActor);

        // send 15 messages
        for n in 5..20 {
            // As there are 4 threads,there are at least 4 messages always being processed
            // concurrently by the SyncActor.
            println!("Sending fibo message");
            addr.do_send(Fibonacci(n));
        }


        // This does not wotk
        //thread::spawn(move || {
        //    thread::sleep(Duration::from_secs_f32(10f32));
        //}).join();

        // This made it worked
        tokio::signal::ctrl_c().await.unwrap();
        println!("Ctrl-C received,shutting down");
        System::current().stop();

    });
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?