为什么`tokio :: main`报告错误“处理时检测到循环”?

问题描述 投票:0回答:1

我正在使用Tokio和async / .await创建一个UDP服务器,可以在其中以异步方式接收和发送数据。

我的UDP套接字的SendHalf在多个任务中共享。为此,我正在使用Arc<Mutex<SendHalf>>。这就是Arc<Mutex<_>>存在的原因。

use tokio::net::UdpSocket;
use tokio::net::udp::SendHalf;
use tokio::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::net::SocketAddr;

struct Packet {
    sender: Arc<Mutex<SendHalf>>,
    buf: [u8; 512],
    addr: SocketAddr,
}

#[tokio::main]
async fn main() {
    let server = UdpSocket::bind(("0.0.0.0", 44667)).await.unwrap();
    let (mut server_rx, mut server_tx) = server.split();
    let sender = Arc::new(Mutex::new(server_tx));
    let (mut tx, mut rx) = mpsc::channel(100);

    tokio::spawn(async move {
        loop {
            let mut buffer = [0; 512];
            let (_, src) = server_rx.recv_from(&mut buffer).await.unwrap();
            let packet = Packet {
                sender: sender.clone(),
                buf: buffer,
                addr: src,
            };
            tx.send(packet).await;
        }
    });

    while let Some(packet) = rx.recv().await {
        tokio::spawn(async move {
            let mut socket = packet.sender.lock().unwrap();
            socket.send_to(&packet.buf, &packet.addr).await.unwrap();
        });
    }
}

这里也是Playground

我遇到了我不理解的编译器错误:

error[E0391]: cycle detected when processing `main`
  --> src/main.rs:13:1
   |
13 | #[tokio::main]
   | ^^^^^^^^^^^^^^
   |
note: ...which requires processing `main::{{closure}}#0::{{closure}}#1`...
  --> src/main.rs:34:33
   |
34 |           tokio::spawn(async move {
   |  _________________________________^
35 | |             let mut socket = packet.sender.lock().unwrap();
36 | |             socket.send_to(&packet.buf, &packet.addr).await.unwrap();
37 | |         });
   | |_________^
   = note: ...which again requires processing `main`, completing the cycle
note: cycle used when processing `main::{{closure}}#0`
  --> src/main.rs:13:1
   |
13 | #[tokio::main]
   | ^^^^^^^^^^^^^^

为什么我的代码产生一个循环?为什么呼叫需要处理main

错误更详细地表示什么?我想了解发生了什么。

rust async-await udp rust-tokio
1个回答
2
投票

根据tokio文档,关于using !Send value from a task

在对!Send的调用中保持!Send的值将导致不友好的编译错误消息,类似于:

.await

或:

[... some type ...] cannot be sent between threads safely

您正在目睹这个确切的错误。当您error[E0391]: cycle detected when processing main

lock a Mutex

它返回Mutex,即pub fn lock(&self) -> LockResult<MutexGuard<T>>

MutexGuard

这可以很好地编译:

MutexGuard
© www.soinside.com 2019 - 2024. All rights reserved.