Store
Source and Output
"""Example: store with heterogeneous items and filter-based retrieval."""
from asimpy import Environment, Process, Store
from _util import example
ITEMS = ["red", "blue", "red", "blue", "red"] # items added at t=1, 2, 3, 4, 5
class Stacker(Process):
"""Adds items to the store one per tick."""
def init(self, store):
self._store = store
async def run(self):
for item in ITEMS:
await self.timeout(1)
await self._store.put(item)
self._env.log("stacker", f"put {item}")
class RedPicker(Process):
"""Retrieves only red items from the store."""
def init(self, store):
self._store = store
async def run(self):
for _ in range(3):
item = await self._store.get(filter=lambda x: x == "red")
self._env.log("red-picker", f"got {item}")
class BluePicker(Process):
"""Retrieves only blue items from the store."""
def init(self, store):
self._store = store
async def run(self):
for _ in range(2):
item = await self._store.get(filter=lambda x: x == "blue")
self._env.log("blue-picker", f"got {item}")
def main():
env = Environment()
store = Store(env)
Stacker(env, store)
RedPicker(env, store)
BluePicker(env, store)
env.run()
return env
if __name__ == "__main__":
example(main)
| time | name | event |
|---|---|---|
| 1 | stacker | put red |
| 1 | red-picker | got red |
| 2 | stacker | put blue |
| 2 | blue-picker | got blue |
| 3 | stacker | put red |
| 3 | red-picker | got red |
| 4 | stacker | put blue |
| 4 | blue-picker | got blue |
| 5 | stacker | put red |
| 5 | red-picker | got red |
Key Points
-
Storeholds heterogeneous items and supports selective retrieval.get(filter=fn)returns the first item for whichfn(item)isTrue. IffilterisNone, any item is accepted. -
If no matching item is available the caller blocks until a subsequent
put()delivers one. Both pickers are already waiting when the stacker puts the first item at t=1. -
Items are matched in insertion order: the first red item is returned to the first red-picker waiting, and so on.
-
Unlike
Queue, items do not need to be comparable. The store is a plain list searched linearly by the filter function.
Check for Understanding
What would get() return if called without a filter while the store contained
both "red" and "blue" items?