Reference Manual
Triggers
Collection of tools for concurrency and synchronization in cocotb.
- class coconext.triggers.Notify
Notify all waiters of an event.
cocotb.triggers.Eventhas state. It can be in the state whereEvent.is_set()isFalseand callingEvent.wait()will return a Trigger that only fires afterEvent.set()is called. Or it can be in a state whereEvent.is_set()isTrueand callingEvent.wait()will return a Trigger that fires immediately.This object does not have state. It behaves like
Eventif it were only ever in theEvent.is_set()isFalsestate. All calls towait()will block until the next call tonotify()occurs.Added in version 0.1.
- class coconext.triggers.TaskManager
An asynchronous context manager which enables the user to run coroutine functions or
awaitawaitables concurrently and wait for them all to finish.awaitables can be added to the
TaskManagerusingstart_soon(). Likewise,fork()can be used to add coroutine functions. Both methods return theTaskwhich is running the concurrent behavior.When control reaches the end of the context block the
TaskManagerblocks theTaskusing it until all childrenTasks of theTaskManagercomplete.async with TaskManager() as tm: @tm.fork async def drive(): ... rising_edge = cocotb.start_soon(RisingEdge(dut.clk)) await drive # wait for drive() to end rising_edge.cancel() # cancel a child Task # Control returns here when all child Tasks have completed
- fork(coro: ~collections.abc.Callable[[~P], ~collections.abc.Coroutine[~cocotb.triggers.Trigger, None, ~coconext._task_manager.T]], *args: ~typing.~P, **kwargs: ~typing.~P) Task[T]
Decorate a coroutine function to run it concurrently.
- Parameters:
coro – A coroutine function to run concurrently.
args – Positional args to pass to the call of coro.
kwargs – Keyword args to pass to the call of coro.
- Returns:
A
Taskwhich is running coro concurrently.
async with TaskManager() as tm: @tm.fork async def my_func(): # Do stuff ... @tb.fork async def other_func(): # Do other stuff in parallel to my_func ...
- async coconext.triggers.gather(*awaitables: Awaitable[Any], return_exceptions: bool = False) tuple[Any, ...]
Awaits on all given awaitables concurrently and returns their results once all have completed.
After the return conditions, based on return_exceptions is met, remaining waiter tasks are cancelled. This does not cancel
Tasks passed as arguments, only the internal tasks awaiting upon their completion.- Parameters:
awaitables – The
Awaitables to concurrentlyawaitupon.return_exceptions – If
False(default), after the first awaitable results in an exception, cancels the remaining awaitables and re-raises the exception. IfTrue, returns the exception rather than the result value when an awaitable results in an exception.
- Returns:
A tuple of the results of awaiting each awaitable in the same order they were given. The order of the return tuple corresponds to the order of the input.
- async coconext.triggers.select(*awaitables: Awaitable[T], return_exception: bool = False) tuple[int, T | BaseException]
Awaits on all given awaitables concurrently and returns the index and result of the first to complete.
After the first awaitable completes, remaining waiter tasks are cancelled. This does not cancel
Tasks passed as arguments, only the internal tasks awaiting upon their completion.- Parameters:
awaitables – The
Awaitables to concurrentlyawaitupon.return_exception – If
False(default), re-raises the exception when an awaitable results in an exception. IfTrue, returns the exception rather than re-raising when an awaitable results in an exception.
- Raises:
ValueError – if missing at least one awaitable.
- Returns:
A tuple of the index into the argument list (0-based) of the first awaitable to complete and its result.
- async coconext.triggers.wait(*awaitables: Awaitable[Any], return_when: Literal['FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED']) tuple[Task[Any], ...]
Awaits on all given awaitables concurrently and blocks until the return_when condition is met.
Every
Awaitablegiven to the function isawaited concurrently in its ownTask. When the return conditions specified by return_when are met, this function returns thoseTasks. Once the return conditions are met, anyTasks which are still running arecancel()ed.The return_when conditions must be one of the following:
"FIRST_COMPLETED": Returns after the first awaitable completes, regardless if that was due to an exception or not."FIRST_EXCEPTION": Returns after all awaitables complete or after the first awaitable that completes due to an exception."ALL_COMPLETED": Returns after all awaitables complete.
- Parameters:
awaitables – The
Awaitables to concurrentlyawaitupon.return_when – The condition that must be met before returning. One of
"FIRST_COMPLETED","FIRST_EXCEPTION", or"ALL_COMPLETED".
- Returns:
A tuple of waiter
Tasks. The order of the return tuple corresponds to the order of the input.
SimTime
Collections of tools for dealing with simulation time in cocotb.
- class coconext.simtime.SimTime(time: float, unit: Literal['fs', 'ps', 'ns', 'us', 'ms', 'sec', 'step'], *, round_mode: Literal['error', 'round', 'ceil', 'floor'] = 'error')
Type for dealing with simulated time.
SimTimeis time quantized to simulator steps. If you can create aSimTime, you have a time that can be represented by the simulator. The type also includes a collection of functionality commonly needed when dealing with time, such as comparison, scaling, and arithmetic.- __init__(time: float, unit: Literal['fs', 'ps', 'ns', 'us', 'ms', 'sec', 'step'], *, round_mode: Literal['error', 'round', 'ceil', 'floor'] = 'error') None
Construct a SimTime of time value in unit.
- Parameters:
time – The time value.
unit – Unit for time argument.
round_mode – How to round the time if it can’t be accurately represented. One of
"error","round","ceil", and"floor". Seecocotb.utils.get_sim_steps()for details on these values.
- in_unit(unit: Literal['fs', 'ps', 'ns', 'us', 'ms', 'sec', 'step']) float
Return time in the given unit.
- mul(other: float, *, round_mode: Literal['error', 'round', 'ceil', 'floor'] = 'error') SimTime
Scale the time via multiplication and supply a round_mode.
Queue
Collection of asynchronous queues for cocotb.
- class coconext.queue.AbstractQueue(maxsize: int = 0)
An asynchronous queue, useful for coordinating producer and consumer tasks.
Queues can have various semantics with respect to the values
put()andget()from them. This class does not enforce any particular semantics, but leaves the implementation and semantics abstract. A concrete queue class can be created by subclassingAbstractQueueand filling in the_size(),_put(),_get(), and_peek()methods.Additionally, there are common implementations included in this module:
Queue(FIFO semantics),LifoQueue(LIFO semantics), andPriorityQueue(min-heap semantics).Added in version 0.2.
- class Lock
A mutex lock specialized for use by asynchronous Queue.
This class is not intended to be instantiated by the user, but rather be acquired via
AbstractQueue.write_lockorAbstractQueue.read_lock.In addition to all the functionality available on
Lock, these locks are aware of the associated queue’s availability, i.e. whether the read or write side has data or space available to either get or put, respectively.- async Lock.acquire() None
Acquire the lock.
Waits until the lock is available and unlocked, sets it to locked and returns. Multiple Tasks may attempt to acquire the Lock, but only one will proceed. Tasks are guaranteed to acquire the Lock in the order each attempts to acquire it.
- Lock.release() None
Release the lock.
Sets the lock to unlocked.
- Raises:
RuntimeError – If called when the lock is unlocked.
- __init__(maxsize: int = 0) None
Construct a queue with the given maxsize.
If maxsize is less than or equal to 0, the queue size is infinite. If it is an integer greater than 0, then
put()will block when the queue reaches maxsize, until an item is removed byget().
- property write_lock: Lock
Lock for exclusive write access.
After acquiring this lock, the user has exclusive access to the write-side of the queue until the lock is released. Calling
put()while the write lock is acquired will result in aRuntimeErrorto prevent deadlock.
- property read_lock: Lock
Lock for exclusive read access.
After acquiring this lock, the user has exclusive access to the read-side of the queue until the lock is released. Calling
get()while the read lock is acquired will result in aRuntimeErrorto prevent deadlock.
- full() bool
Return
Trueif there aremaxsize()items in the queue.Note
If the Queue was initialized with
maxsize=0(the default), thenfull()is neverTrue.
- async put(item: T) None
Put an item into the queue.
If the queue is full, wait until a free slot is available before adding the item.
- put_nowait(item: T) None
Put an item into the queue without blocking.
If no free slot is immediately available, raise
QueueFull.
- async get() T
Remove and return an item from the queue.
If the queue is empty, wait until an item is available.
- get_nowait() T
Remove and return an item from the queue.
Returns an item if one is immediately available, otherwise raises
QueueEmpty.
- async peek() T
Return the next item from the queue without removing it.
If the queue is empty, wait until an item is available.
- peek_nowait() T
Return the next item from the queue without removing it.
Returns an item if one is immediately available, otherwise raises
QueueEmpty.
- class coconext.queue.Queue(maxsize: int = 0)
A subclass of
AbstractQueue; retrieves oldest entries first (FIFO).Added in version 2.0.
- class coconext.queue.PriorityQueue(maxsize: int = 0)
A subclass of
AbstractQueue; retrieves entries in priority order (smallest item first).Entries are typically tuples of the form
(priority number, data).Added in version 2.0.
- class coconext.queue.LifoQueue(maxsize: int = 0)
A subclass of
AbstractQueue; retrieves most recently added entries first (LIFO).Added in version 2.0.