Tokio: udp: enable concurrent use of a single UdpSocket from multiple locations

Created on 2 Oct 2019  路  4Comments  路  Source: tokio-rs/tokio

It is common to want to send via a single socket from multiple locations. Because UdpSocket takes &mut self and there is no possibility to clone the socket, this is not possible today.

Previous discusion: #1613, #1624

A-tokio C-enhancement M-net

Most helpful comment

I would find the resolution of this issue very helpful, are there plans to merge #1979 anytime soon?

All 4 comments

so I'm assuming this won't work..?:

pub fn try_clone(&self) -> io::Result<Self> {
    Ok(UdpSocket::new(self.io.get_ref().try_clone()?))
}

If not, what's the general strategy because I already have removed all the &mut self -> &self as well as change the tests. This seems to work on the surface (as far as the compiler cares..) but I noticed it gives them different file descriptors when it clones it.. but they are associated with the same ip/port it seems.

There was some sort of talk of a wrapper that serves as a form of indirection, but short of locking, is this possible? The underlying mio::net::UdpSocket is try_clone'able, so I figured this might be good enough.

Any guidance you guys have would be appreciated. Trying to lend a hand to a project I really appreciate.. Thanks

How about using Arc<tokio::sync::Mutex<UdpSocketSendHalf>>?

Or (cross post from #1108) we can provide a synchronized UdpSocket:

struct UdpSocket {
    socket: PollEvented<mio::net::UdpSocket>,
    send_lock: tokio::sync::Mutex<()>,
    recv_lock: tokio::sync::Mutex<()>,
}

impl UdpSocket {
    pub async fn send_to(&self, ...) -> ... {
        let _send_lock_guard = self.send_lock.lock().await;
        poll_fn(...).await
    }
}

@bryandmc It's because clone uses dup to duplicate the file descriptor

I would find the resolution of this issue very helpful, are there plans to merge #1979 anytime soon?

Was this page helpful?
0 / 5 - 0 ratings