Search code examples
pythonmultithreadingloopsmpitheory

Can 2 for loops be run simultaneously, looping one after the other?


I was just wondering, how would you create a loop such that each iteration occurs one after the other? I am aware that multi threading is a thing, and I am familiar with it. One thing I cannot figure out is how to run one loop after another.

For example, say I had 2 functions:

def loop_a():
    while True:
        time.sleep(1)
        print("a")

def loop_b():
    while True:
        print("b")

How do i get the output to be ababababababababa, even with the time.sleep(1) present in the first function?

I am using mpi4py, and was wondering if there was any way to do this using this library. My actual program requires messages to be sent between functions. Otherwise, using any other python libraries such as multiprocessing should be fine.

Is there a way to do this using threading?


Solution

  • import asyncio
    
    q = asyncio.Queue()
    
    async def loop_a(q):
      for i in range(10):
        value = await q.get()
        print(value)
    
    async def loop_b(q):
      for i in range(10):
        await q.put("a")
        print("b")
    
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(loop_a(q), loop_b(q)))