-
Notifications
You must be signed in to change notification settings - Fork 3
feat: implement Single-Producer-Single-Consumer Ring Buffer #7
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
Merged
Merged
Changes from all commits
Commits
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 hidden or 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 |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| version: 2 | ||
|
|
||
|
|
||
| updates: | ||
| - package-ecosystem: cargo | ||
| directory: "/" | ||
| schedule: | ||
| interval: daily | ||
| time: "02:00" | ||
| open-pull-requests-limit: 10 | ||
| - package-ecosystem: github-actions | ||
| directory: "/" | ||
| schedule: | ||
| interval: daily | ||
| time: "02:00" | ||
| open-pull-requests-limit: 10 |
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| name: CI | ||
| on: pull_request | ||
|
|
||
| env: | ||
| CARGO_TERM_COLOR: always | ||
|
|
||
| jobs: | ||
| format: | ||
| name: format | ||
| runs-on: ubuntu-latest | ||
| steps: | ||
| - uses: actions/checkout@v4 | ||
| - uses: dtolnay/rust-toolchain@stable | ||
| with: | ||
| components: clippy | ||
| - uses: Swatinem/rust-cache@v2 | ||
| - run: make format | ||
|
|
||
| check: | ||
| name: check | ||
| runs-on: ubuntu-latest | ||
| steps: | ||
| - uses: actions/checkout@v4 | ||
| - uses: dtolnay/rust-toolchain@stable | ||
| - uses: Swatinem/rust-cache@v2 | ||
| - run: make check | ||
|
|
||
| base-test: | ||
| name: base-test | ||
| runs-on: ubuntu-latest | ||
| steps: | ||
| - uses: actions/checkout@v4 | ||
| - uses: dtolnay/rust-toolchain@stable | ||
| - uses: Swatinem/rust-cache@v2 | ||
| - run: make base-test | ||
|
|
||
| loom: | ||
| name: loom | ||
| runs-on: ubuntu-latest | ||
| steps: | ||
| - uses: actions/checkout@v4 | ||
| - uses: dtolnay/rust-toolchain@stable | ||
| - uses: Swatinem/rust-cache@v2 | ||
| - run: make loom | ||
|
|
||
| miri-spinlock: | ||
| name: miri / SpinLock | ||
| runs-on: ubuntu-latest | ||
| timeout-minutes: 10 | ||
| steps: | ||
| - uses: actions/checkout@v4 | ||
| - uses: dtolnay/rust-toolchain@nightly | ||
| with: | ||
| components: miri | ||
| - uses: Swatinem/rust-cache@v2 | ||
| - run: make miri-spinlock | ||
|
|
||
| miri-spscringbuffer: | ||
| name: miri / SPSCRingBuffer + SPSCRingBufferV2 | ||
| runs-on: ubuntu-latest | ||
| timeout-minutes: 10 | ||
| steps: | ||
| - uses: actions/checkout@v4 | ||
| - uses: dtolnay/rust-toolchain@nightly | ||
| with: | ||
| components: miri | ||
| - uses: Swatinem/rust-cache@v2 | ||
| - run: make miri-spscringbuffer |
This file contains hidden or 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
This file contains hidden or 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 |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| mod spinlock; | ||
| mod spscringbuffer; | ||
| mod spscringbufferv2; | ||
| mod sync; | ||
|
|
||
| fn main() { | ||
|
|
||
This file contains hidden or 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 |
|---|---|---|
| @@ -1 +1,133 @@ | ||
| // TODO: ну ето, надо | ||
| use crate::sync::{AtomicUsize, Ordering}; | ||
|
|
||
| use std::cell::UnsafeCell; | ||
| use std::ptr; | ||
|
|
||
| /// Single-Producer-Single-Consumer Ring Buffer | ||
| #[allow(dead_code)] | ||
| pub struct SPSCRingBuffer<T> { | ||
| capacity: usize, | ||
| buffer: UnsafeCell<Box<[T]>>, | ||
| head: AtomicUsize, | ||
| tail: AtomicUsize, | ||
| } | ||
|
|
||
| unsafe impl<T: Send> Send for SPSCRingBuffer<T> {} | ||
| unsafe impl<T: Send> Sync for SPSCRingBuffer<T> {} | ||
|
|
||
| #[allow(dead_code)] | ||
| impl<T> SPSCRingBuffer<T> | ||
| where | ||
| T: Copy + Default, | ||
| { | ||
| pub fn new(capacity: usize) -> Self { | ||
| let buffer = vec![T::default(); capacity].into_boxed_slice(); | ||
| Self { | ||
| capacity, | ||
| buffer: UnsafeCell::new(buffer), | ||
| head: AtomicUsize::new(0), | ||
| tail: AtomicUsize::new(0), | ||
| } | ||
| } | ||
|
|
||
| pub fn try_produce(&self, value: T) -> bool { | ||
| let current_head = self.head.load(Ordering::Acquire); | ||
| let current_tail = self.tail.load(Ordering::Relaxed); | ||
|
|
||
| if self.is_full(current_head, current_tail) { | ||
| return false; | ||
| } | ||
|
|
||
| unsafe { | ||
| let slot_ptr = self.slot_ptr(current_tail); | ||
| ptr::write(slot_ptr, value); | ||
| } | ||
|
|
||
| self.tail.store(self.next(current_tail), Ordering::Release); | ||
|
|
||
| true | ||
| } | ||
|
|
||
| pub fn try_consume(&self) -> Option<T> { | ||
| let current_head = self.head.load(Ordering::Relaxed); | ||
| let current_tail = self.tail.load(Ordering::Acquire); | ||
|
|
||
| if self.is_empty(current_head, current_tail) { | ||
| return None; | ||
| } | ||
|
|
||
| let value = unsafe { | ||
| let slot_ptr = self.slot_ptr(current_head); | ||
| ptr::read(slot_ptr) | ||
| }; | ||
|
|
||
| self.head.store(self.next(current_head), Ordering::Release); | ||
|
|
||
| Some(value) | ||
| } | ||
|
|
||
| /// Возвращает сырой указатель `*mut T` на элемент буфера по заданному индексу. | ||
| /// | ||
| /// Обходит создание промежуточных ссылок (`&` / `&mut`) на весь слайс, | ||
| /// чтобы не нарушать правила Stacked Borrows при одновременном доступе | ||
| /// из потока-производителя и потока-потребителя к разным элементам буфера. | ||
| /// | ||
| /// `index` должен быть строго меньше `self.capacity`. | ||
| fn slot_ptr(&self, index: usize) -> *mut T { | ||
| unsafe { | ||
| // self.buffer.get() -> *mut Box<[T]> | ||
| // *self.buffer.get() -> Box<[T]> (place expression, без перемещения) | ||
| // Сырой указатель на срез в куче, без промежуточной ссылки | ||
| // &raw mut **self.buffer.get() -> *mut [T] | ||
| let slice_ptr: *mut [T] = &raw mut **self.buffer.get(); | ||
| (slice_ptr as *mut T).add(index) | ||
| } | ||
| } | ||
|
|
||
| fn next(&self, slot: usize) -> usize { | ||
| (slot + 1) % self.capacity | ||
| } | ||
|
|
||
| fn is_full(&self, head: usize, tail: usize) -> bool { | ||
| self.next(tail) == head | ||
| } | ||
|
|
||
| fn is_empty(&self, head: usize, tail: usize) -> bool { | ||
| tail == head | ||
| } | ||
| } | ||
|
|
||
| #[cfg(all(test, not(feature = "sanitizers")))] | ||
| mod tests { | ||
| use super::*; | ||
| use std::sync::Arc; | ||
| use std::thread; | ||
|
|
||
| #[test] | ||
| fn test_concurrent_reads_and_writes() { | ||
| let ring_buffer: Arc<SPSCRingBuffer<i32>> = Arc::new(SPSCRingBuffer::new(42)); | ||
| let producer_buffer = Arc::clone(&ring_buffer); | ||
| let consumer_buffer = Arc::clone(&ring_buffer); | ||
|
|
||
| let values_count = 100500; | ||
|
|
||
| let producer_handle = thread::spawn(move || { | ||
| for i in 0..values_count { | ||
| while !producer_buffer.try_produce(i) { | ||
| // Retry | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| let consumer_handle = thread::spawn(move || { | ||
| for _ in 0..values_count { | ||
| while consumer_buffer.try_consume().is_none() { | ||
| // Retry | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| producer_handle.join().unwrap(); | ||
| consumer_handle.join().unwrap(); | ||
| } | ||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.