`Async and Concurrency` for people in a hurry

I was really struggling with concurrency in panel because due to the nice learning curve, I have hardly any clue of the underlying machinery. Most examples were beyond my level of understanding. I like the param class based approach. Hence here my Jupyter based example:

class DataSource(param.Parameterized):
    @brief  Simulation of an external data source, e.g. measurement instrument, for parallel data acquisition.
    acquire = param.Boolean(default=True, doc="Data acquisition status")
    run = param.Boolean(default=True, doc="Running status of async task")
    counter = param.Integer(default=0, doc="Dummy data")
    def __init__(self, **params):
        # Necessary only if `Jupyter` is used. In Python: `asyncio.create_task(self._get_data())`
        jupyter_loop = asyncio.get_running_loop()
    async def _get_data(self):
        while self.run:
            if self.acquire:
                print(f"Data {self.counter}")
                await asyncio.sleep(1)
                self.counter += 1
                print(f"Waiting ...")
                await asyncio.sleep(1)
data_source = DataSource()

Control with:

data_source.acquire = False  # Wait for "data", then pause acquisition
data_source.acquire = True  # Start again
data_source.run = False  # End task

panel version:

class DataSourcePn(DataSource):
    def __init__(self, **params):
    def dashboard(self):
        return pn.panel(self.param)

Any feedback is welcome.

PS: I borrowed the title from a book by Neil deGrasse Tyson

1 Like