Module spsc

Module spsc 

Source
Expand description

High-performance async SPSC (Single Producer Single Consumer) channel

Built on top of smallring - a high-performance ring buffer with inline storage support. Optimized for low latency and fast creation, designed to replace tokio mpsc in timer implementation. The N const generic parameter allows specifying inline buffer size for zero-allocation small channels.

高性能异步 SPSC(单生产者单消费者)通道

基于 smallring 构建 - 一个支持内联存储的高性能环形缓冲区。 针对低延迟和快速创建进行优化,用于替代定时器实现中的 tokio mpsc。 N 常量泛型参数允许指定内联缓冲区大小,实现小容量通道的零分配。

§安全性说明 (Safety Notes)

本实现使用 UnsafeCell 来提供零成本内部可变性,而不是 Mutex。 这是安全的,基于以下保证:

  1. 单一所有权SenderReceiver 都不实现 Clone,确保每个通道只有一个发送者和一个接收者
  2. 访问隔离Producer 只被唯一的 Sender 访问,Consumer 只被唯一的 Receiver 访问
  3. 无数据竞争:由于单一所有权,不会有多个线程同时访问同一个 ProducerConsumer
  4. 原子通信ProducerConsumer 内部使用原子操作进行跨线程通信
  5. 类型系统保证:通过类型系统强制 SPSC 语义,防止误用为 MPMC

这种设计实现了零同步开销,完全消除了 Mutex 的性能损失。

§Safety Guarantees

This implementation uses UnsafeCell for zero-cost interior mutability instead of Mutex. This is safe based on the following guarantees:

  1. Single Ownership: Neither Sender nor Receiver implements Clone, ensuring only one sender and one receiver per channel
  2. Access Isolation: Producer is only accessed by the unique Sender, Consumer only by the unique Receiver
  3. No Data Races: Due to single ownership, there’s no concurrent access to the same Producer or Consumer
  4. Atomic Communication: Producer and Consumer use atomic operations internally for cross-thread communication
  5. Type System Enforcement: SPSC semantics are enforced by the type system, preventing misuse as MPMC

This design achieves zero synchronization overhead, completely eliminating Mutex performance costs.

Structs§

Drain
Draining iterator for the SPSC channel
Receiver
SPSC channel receiver
Sender
SPSC channel sender

Enums§

SendError
Send error type
TryRecvError
Try-receive error type
TrySendError
Try-send error type

Functions§

channel
SPSC channel creation function