Skip to content

How do I make two kinds of entity wait for each other?

A ride needs a rider and a driver, and each waits until the other is there. MATCH holds each kind until a full set is present. The script matches one rider with one driver.

from nagasim import build as nb

# Riders and drivers arrive at random. MATCH with number_to_match=2 holds each one until the other
# kind is there, then releases the pair together. Riders come every 3 minutes and drivers every 4,
# so riders queue for a driver and some are still waiting when the run ends.
m = nb.Model(time_limit=300)
m.add_entity(name="RIDER")
m.add_entity(name="DRIVER")
riders = m.create("Riders", e_type="RIDER", distribution=nb.Exponential(rate=1 / 3))
drivers = m.create("Drivers", e_type="DRIVER", distribution=nb.Exponential(rate=1 / 4))
ride = m.match("Ride", number_to_match=2)
riders >> ride
drivers >> ride
ride >> m.delay(distribution=nb.Constant(value=1)) >> m.dispose()

summary = m.run(seed=1)["entity_summary"]
print(summary[["Entity Type", "Total Created", "Total Completed", "Avg Time"]].round(1).to_string(index=False))

Save it as recipe-pair-flows.py and run it with python. The script seeds itself, so the numbers below are the same on your machine.

Entity Type  Total Created  Total Completed  Avg Time
     DRIVER             76               76       1.0
      RIDER             99               76      28.0

How it works

  1. m.match(number_to_match=2) waits for one entity of each type that reaches it, then releases them together.
  2. Riders arrive every 3 minutes and drivers every 4, so the riders queue: 99 were created and 76 matched.
  3. The side that arrives more often builds the queue, so a long wait for one kind shows where to add capacity.

Elements used

Back to all recipes.