Run several testbench activities in parallel and choose the right synchronization mechanism.
A testbench often drives, observes, and watches for timeouts in parallel. Each activity needs synchronization and a termination rule; a missed notification can otherwise stall the whole test.
Start and stop threads
fork
drive_requests();
monitor_responses();
watch_timeout();
join
join waits for all branches, join_any for the first to finish, and join_none lets the parent continue. After join_any, explicitly stop remaining activities when they are no longer needed.
In a loop, capture the index before starting each child:
for (int port = 0; port < 4; port++) begin automatic int selected_port = port; fork monitor_port(selected_port); join_noneendwait fork;
automatic gives every iteration its own value. With join_none, children start when the parent yields execution. wait fork waits for children of the current thread; that may include more than the intended group.
disable fork can also stop unrelated descendants. Isolate the group in a dedicated process or use an appropriate named block.
Notify without storing
event reset_done;fork begin apply_reset(); -> reset_done; end begin @reset_done; start_traffic(); endjoin
-> triggers the event; @reset_done waits for the next trigger. A notification before the wait is lost. Use a persistent variable with wait(condition) when state must be remembered.
wait(reset_done.triggered) sees a trigger in the current time step. Before reusing it in a loop, wait for a timed event to avoid a zero-time loop. An event does not count multiple occurrences.
A mailbox is a typed FIFO. put and get can block; try_put, try_get, and try_peek immediately report success or failure. A bounded mailbox limits producer lead.
It passes handles without copying objects. Send a new object or copy before modifying the original. Capacity one does not ensure lockstep processing: the consumer can remove an item and process it while the next arrives. A separate acknowledgement, or peek followed by processing and get, can provide that coordination.
Do not split num() and get to decide whether removal is possible; another thread can intervene. Use get or try_get directly.
A semaphore holds keys. One key acts as a lock; return exactly the keys acquired, including on error paths. It protects access without carrying commands or results.
Choose fork for activities, events for transient notifications, mailboxes for data, and semaphores for shared access. Add timeouts to waits that may never complete.