-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
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
sync::broadcast: create Sender::new #5824
Merged
Darksonn
merged 2 commits into
tokio-rs:master
from
marcospb19:create-constructor-sender-new
Jul 15, 2023
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -444,42 +444,13 @@ const MAX_RECEIVERS: usize = usize::MAX >> 2; | |
/// This will panic if `capacity` is equal to `0` or larger | ||
/// than `usize::MAX / 2`. | ||
#[track_caller] | ||
pub fn channel<T: Clone>(mut capacity: usize) -> (Sender<T>, Receiver<T>) { | ||
assert!(capacity > 0, "capacity is empty"); | ||
assert!(capacity <= usize::MAX >> 1, "requested capacity too large"); | ||
|
||
// Round to a power of two | ||
capacity = capacity.next_power_of_two(); | ||
|
||
let mut buffer = Vec::with_capacity(capacity); | ||
|
||
for i in 0..capacity { | ||
buffer.push(RwLock::new(Slot { | ||
rem: AtomicUsize::new(0), | ||
pos: (i as u64).wrapping_sub(capacity as u64), | ||
val: UnsafeCell::new(None), | ||
})); | ||
} | ||
|
||
let shared = Arc::new(Shared { | ||
buffer: buffer.into_boxed_slice(), | ||
mask: capacity - 1, | ||
tail: Mutex::new(Tail { | ||
pos: 0, | ||
rx_cnt: 1, | ||
closed: false, | ||
waiters: LinkedList::new(), | ||
}), | ||
num_tx: AtomicUsize::new(1), | ||
}); | ||
|
||
pub fn channel<T: Clone>(capacity: usize) -> (Sender<T>, Receiver<T>) { | ||
// SAFETY: In the line below we are creating one extra receiver, so there will be 1 in total. | ||
let tx = unsafe { Sender::new_with_receiver_count(1, capacity) }; | ||
let rx = Receiver { | ||
shared: shared.clone(), | ||
shared: tx.shared.clone(), | ||
next: 0, | ||
}; | ||
|
||
let tx = Sender { shared }; | ||
|
||
(tx, rx) | ||
} | ||
|
||
|
@@ -490,6 +461,65 @@ unsafe impl<T: Send> Send for Receiver<T> {} | |
unsafe impl<T: Send> Sync for Receiver<T> {} | ||
|
||
impl<T> Sender<T> { | ||
/// Creates the sending-half of the [`broadcast`] channel. | ||
/// | ||
/// See documentation of [`broadcast::channel`] for errors when calling this function. | ||
/// | ||
/// [`broadcast`]: crate::sync::broadcast | ||
/// [`broadcast::channel`]: crate::sync::broadcast | ||
#[track_caller] | ||
pub fn new(capacity: usize) -> Self { | ||
// SAFETY: We don't create extra receivers, so there are 0. | ||
unsafe { Self::new_with_receiver_count(0, capacity) } | ||
} | ||
|
||
/// Creates the sending-half of the [`broadcast`](self) channel, and provide the receiver | ||
/// count. | ||
/// | ||
/// See the documentation of [`broadcast::channel`](self::channel) for more errors when | ||
/// calling this function. | ||
/// | ||
/// # Safety: | ||
/// | ||
/// The caller must ensure that the amount of receivers for this Sender is correct before | ||
/// the channel functionalities are used, the count is zero by default, as this function | ||
/// does not create any receivers by itself. | ||
#[track_caller] | ||
unsafe fn new_with_receiver_count(receiver_count: usize, mut capacity: usize) -> Self { | ||
Comment on lines
+487
to
+488
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since this is an unsafe method, it should have a comment that explains what the safety requirements are. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. + /// Creates the sending-half of the [`broadcast`] channel, and provide the receiver count.
+ ///
+ /// See the documentation of [`broadcast::channel`] for more errors when calling this
+ /// function.
+ ///
+ /// # Safety:
+ ///
+ /// The caller must ensure that the amount of receivers for this Sender is correct before
+ /// the channel functionalities are used, the count is zero by default, as this function
+ /// does not create any receivers by itself. |
||
assert!(capacity > 0, "broadcast channel capacity cannot be zero"); | ||
assert!( | ||
capacity <= usize::MAX >> 1, | ||
"broadcast channel capacity exceeded `usize::MAX / 2`" | ||
); | ||
|
||
// Round to a power of two | ||
capacity = capacity.next_power_of_two(); | ||
|
||
let mut buffer = Vec::with_capacity(capacity); | ||
|
||
for i in 0..capacity { | ||
buffer.push(RwLock::new(Slot { | ||
rem: AtomicUsize::new(0), | ||
pos: (i as u64).wrapping_sub(capacity as u64), | ||
val: UnsafeCell::new(None), | ||
})); | ||
} | ||
|
||
let shared = Arc::new(Shared { | ||
buffer: buffer.into_boxed_slice(), | ||
mask: capacity - 1, | ||
tail: Mutex::new(Tail { | ||
pos: 0, | ||
rx_cnt: receiver_count, | ||
closed: false, | ||
waiters: LinkedList::new(), | ||
}), | ||
num_tx: AtomicUsize::new(1), | ||
}); | ||
|
||
Sender { shared } | ||
} | ||
|
||
/// Attempts to send a value to all active [`Receiver`] handles, returning | ||
/// it back if it could not be sent. | ||
/// | ||
|
@@ -1369,3 +1399,41 @@ impl<'a, T> Drop for RecvGuard<'a, T> { | |
} | ||
|
||
fn is_unpin<T: Unpin>() {} | ||
|
||
#[cfg(not(loom))] | ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn receiver_count_on_sender_constructor() { | ||
let sender = Sender::<i32>::new(16); | ||
assert_eq!(sender.receiver_count(), 0); | ||
|
||
let rx_1 = sender.subscribe(); | ||
assert_eq!(sender.receiver_count(), 1); | ||
|
||
let rx_2 = rx_1.resubscribe(); | ||
assert_eq!(sender.receiver_count(), 2); | ||
|
||
let rx_3 = sender.subscribe(); | ||
assert_eq!(sender.receiver_count(), 3); | ||
|
||
drop(rx_3); | ||
drop(rx_1); | ||
assert_eq!(sender.receiver_count(), 1); | ||
|
||
drop(rx_2); | ||
assert_eq!(sender.receiver_count(), 0); | ||
} | ||
|
||
#[cfg(not(loom))] | ||
#[test] | ||
fn receiver_count_on_channel_constructor() { | ||
let (sender, rx) = channel::<i32>(16); | ||
assert_eq!(sender.receiver_count(), 1); | ||
|
||
let _rx_2 = rx.resubscribe(); | ||
assert_eq!(sender.receiver_count(), 2); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The two calls to this method should have a SAFETY comment that explains why the code is correct.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
and