0

I want do two functions at same time That the end is related to each other For example :

def func1 ():
    while True:
        print('it fine')

That this is only for beauty and does not do anything special.

But the next function plays the main role of the program and I want func1 to run until it is finished.

def func2():
    number=1000
    for i in range(number):
        if i % 541 ==0:
            print('Horay !!!')
            return

Well, here are two questions, one is how can I do this and two can I get out of func1?

i need output like this :

it fine
it fine
it fine
it fine
it fine
it fine
it fine
it fine
it fine
Horay !!!

But I want exactly use two Function.

Sir-Sorg
  • 175
  • 1
  • 2
  • 10

1 Answers1

2

I have rewritten your sample using asyncio. Pay attention to several points:

  • Using async def declarations
  • Concurrent coroutines are started by create_task()
  • Coroutines should use at least one await invocation within to allow concurrent coroutines to be executed cooperatively. (Pay attention to await asyncio.sleep())

For deeper understanding refer you to this post and official documentation.

import asyncio


async def func1():
    while True:
        print('it fine')
        await asyncio.sleep(0)


async def func2():
    number = 1000
    task = asyncio.create_task(func1())  # run concurrent task
    for i in range(1, number):
        if i % 541 == 0:
            print('Horay !!!')
            task.cancel()  # stop task
            return
        await asyncio.sleep(0)

asyncio.run(func2())  # run program entrypoint coroutine
...
it fine
it fine
it fine
it fine
it fine
it fine
Horay !!!
alex_noname
  • 26,459
  • 5
  • 69
  • 86
  • woow its work correct,But I can not fully understand it, can you please tell me where you learned in addition suggest a good source. – Sir-Sorg Jan 16 '21 at 10:22