Edward Chang
Edward Chang

Reputation: 151

Does Python have any equivalents to Rust's multi-producer single-consumer (MPSC) channels?

I would like to have a Python function that creates a transmitter / receiver channel pair with the same or similar mechanism as Rust:

These channels come in two flavors:

  1. An asynchronous, infinitely buffered channel. The channel function will return a (Sender, Receiver) tuple where all sends will be asynchronous (they never block). The channel conceptually has an infinite buffer.

  2. A synchronous, bounded channel. The sync_channel function will return a (SyncSender, Receiver) tuple where the storage for pending messages is a pre-allocated buffer of a fixed size. All sends will be synchronous by blocking until there is buffer space available. Note that a bound of 0 is allowed, causing the channel to become a "rendezvous" channel where each sender atomically hands off a message to a receiver.

Upvotes: 0

Views: 791

Answers (1)

user4815162342
user4815162342

Reputation: 155256

Create a queue.Queue and you'll get an object that represents both sides of the channel. Pass it to your threads and call q.get() to receive and q.put(item) to send. There is no notion of closing the channel (achieved in Rust by dropping all producers), you'll need to send a sentinel value like None.

Upvotes: 0

Related Questions