Pause the main thread during the execute callback function

Question:

I am trying to use page.on to listening certain event, and once it is triggered I want to use callback function to handle it and pause the main thread operation till the callback finished. How can I achieve that? So far it is what I got here:

async def mission(self):
    async def handler(request):
        try:
            if "https://some_request.com" in request.url:
                await Solution(page=self.page).resolve()

    logger.info('Main operation')
    self.page.on('request', handler)
    logger.info('Main operation')

The callback can pause the main thread.

Asked By: Ziqi Xiao

||

Answers:

That is a typical use case for a "Lock" (https://docs.python.org/3/library/asyncio-sync.html#lock ) – It can only be acquired if it is not acquired somewhere else. Combined with the async with command, it guards blocks of code so that they are executed exclusively.

If you break your "main operation" in various parts, just acquire the lock
before it part that can not run concurrently with the handler:

from asyncio import Lock
...

async def mission(self):
    lock = Lock()
    async def handler(request):
        async with lock:
            if "https://some_request.com" in request.url:
                await Solution(page=self.page).resolve()

    
    # register handler:
    self.page.on('request', handler)
    logger.info('Main operation start')
    while True:
        async with lock:
            logger.info("step of main operation")
            
...
Answered By: jsbueno