Semaphores on Python

后端 未结 4 1104
无人共我
无人共我 2020-12-29 22:24

I\'ve started programming in Python a few weeks ago and was trying to use Semaphores to synchronize two simple threads, for learning purposes. Here is what I\'ve got:

<
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-29 23:19

    In fact, I want to find asyncio.Semaphores, not threading.Semaphore, and I believe someone may want it too.

    So, I decided to share the asyncio.Semaphores, hope you don't mind.

    from asyncio import (
        Task,
        Semaphore,
    )
    import asyncio
    from typing import List
    
    
    async def shopping(sem: Semaphore):
        while True:
            async with sem:
                print(shopping.__name__)
            await asyncio.sleep(0.25)  # Transfer control to the loop, and it will assign another job (is idle) to run.
    
    
    async def coding(sem: Semaphore):
        while True:
            async with sem:
                print(coding.__name__)
            await asyncio.sleep(0.25)
    
    
    async def main():
        sem = Semaphore(value=1)
        list_task: List[Task] = [asyncio.create_task(_coroutine(sem)) for _coroutine in (shopping, coding)]
        """ 
        # Normally, we will wait until all the task has done, but that is impossible in your case.
        for task in list_task:
            await task
        """
        await asyncio.sleep(2)  # So, I let the main loop wait for 2 seconds, then close the program.
    
    
    asyncio.run(main())
    

    output

    shopping
    coding
    shopping
    coding
    shopping
    coding
    shopping
    coding
    shopping
    coding
    shopping
    coding
    shopping
    coding
    shopping
    coding
    

    16*0.25 = 2

提交回复
热议问题