Issue
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.
Solution
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 toawait 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 !!!
Answered By - alex_noname
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.