crossbeam-rs / crossbeam

Tools for concurrent programming in Rust
Apache License 2.0
7.49k stars 470 forks source link

Add force_send method to channel Sender #1135

Open bergkvist opened 2 months ago

bergkvist commented 2 months ago

Add a force_push method to the Sender part of a channel.

In particular, this is useful for bounded channels of non-zero size.

Motivation:

Design goals:

use crossbeam_channel::{bounded, ForceSendError};

let (s, r) = bounded(3);

assert_eq!(s.force_send(0), Ok(None));
assert_eq!(s.force_send(1), Ok(None));
assert_eq!(s.force_send(2), Ok(None));
assert_eq!(s.force_send(3), Ok(Some(2)));

assert_eq!(r.recv(), Ok(0));

assert_eq!(s.force_send(4), Ok(None));

assert_eq!(r.recv(), Ok(1));
assert_eq!(r.recv(), Ok(3));

assert_eq!(s.force_send(5), Ok(None));
assert_eq!(s.force_send(6), Ok(None));
assert_eq!(s.force_send(7), Ok(Some(6)));
assert_eq!(s.force_send(8), Ok(Some(7)));

assert_eq!(r.recv(), Ok(4));
assert_eq!(r.recv(), Ok(5));
assert_eq!(r.recv(), Ok(8));

drop(r);

assert_eq!(s.force_send(9), Err(ForceSendError::Disconnected(9)));