Sharing State

class usim.Lock[source]

Synchronization primitive that may be acquired by only one Activity at a time

Locks enforce mutually exclusive access for Activities, by allowing only one owner at any time. Activities can acquire ownership of a Lock only via an async with context, and automatically release when exiting the block:

async with lock:
    ...

Ownership of a lock is inherently tied to a specific activity; it is not possible to acquire and release a Lock across several activities. Every lock is re-entrant for its owning activity: an Activity can acquire the same lock multiple times. This allows using Locks safely in recursive calls.

property available: bool

Check whether the current Task can acquire this lock

Entering a Lock in its context manager does not allow backing off when the Lock cannot be acquired. Availability of a Lock should be checked if it shall only be acquired when available.

if lock.available:  # only acquire lock if possible
    with lock:
        ...
else:
    ...
class usim.Channel[source]

Unbuffered stream that broadcasts every message to all consumers

await close()[source]

Prevent putting further messages into the Channel

Closing a Channel causes subsequent attempts to put() or retrieve items to fail with StreamClosed.

A Channel can be closed multiple times; subsequent closes have no effects other than postponement.

await put(item: usim._basics.streams.ST)[source]

Put an item into the Channel

Parameters

item – the item to broadcast

Raises

StreamClosed – if the stream has been close()d

class usim.Queue[source]

Buffered stream that anycasts messages to individual consumers

await close()[source]

Prevent putting further messages into the Queue

Closing a Queue causes subsequent attempts to put() items to fail with StreamClosed. When there are no items in a closed Queue, attempts to retrieve items fail with StreamClosed. Items already buffered may still be received.

A Queue can be closed multiple times; subsequent closes have no effects other than postponement.

await put(item: usim._basics.streams.ST)[source]

Put an item into the Queue

Parameters

item – the item to enqueue

Raises

StreamClosed – if the stream has been close()d

exception usim.StreamClosed(stream)[source]