Spsc class final

SPSC (Single-Producer Single-Consumer) channels - Efficient direct communication.

A high-performance channel type in cross_channel. Optimized for scenarios where exactly one producer communicates with exactly one consumer. Uses efficient algorithms and data structures to minimize overhead.

Performance Characteristics

  • Good performance: Efficient message passing, typically ~550-570ns per operation
  • Minimal allocations: Optimized to reduce garbage collection pressure
  • Efficient design: Designed to avoid contention in the hot path
  • Ring buffer: Uses power-of-two sized SRSW (Single-Reader Single-Writer) ring buffer

When to Use SPSC

  • Performance-sensitive producer-consumer scenarios
  • Data streaming between two components
  • Game logic (e.g., main thread ↔ render thread communication)
  • Sensor data processing
  • Any scenario requiring efficient 1:1 communication

Constraints

EXACTLY one producer and one consumer required

  • Violation leads to undefined behavior and potential data corruption
  • Use XChannel.mpsc for multiple producers
  • Use XChannel.mpmc for multiple producers and consumers

Example

import 'dart:async';

import 'package:cross_channel/spsc.dart';

Future<void> main() async {
  // 1. Create a bounded SPSC channel for 1:1 communication
  final (tx, rx) = Spsc.channel<int>(1024);

  // 2. Producer
  Future<void> produceEvents() async {
    for (int i = 0; i < 5; i++) {
      await tx.send(i);
      print('SPSC Sent: $i');
    }
    tx.close(); // Graceful shutdown
  }

  unawaited(produceEvents());

  // 3. Single Consumer
  await for (final value in rx.stream()) {
    print('SPSC Received: $value');
  }
}

Constructors

Spsc()

Properties

hashCode int
The hash code for this object.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited

Static Methods

bounded<T>(int capacity, {String? metricsId}) → (SpscSender<T>, SpscReceiver<T>)
channel<T>(int capacity, {String? metricsId}) SpscChannel<T>
unbounded<T>({bool chunked = true, String? metricsId}) → (SpscSender<T>, SpscReceiver<T>)