python Adding Task Instance Operation in Synergy

  • 2021-09-11 20:54:55
  • OfStack

1. Add a task


task2 = visit_url('http://another.com', 3)
asynicio.run(task2)

2. These two programs 1 consume about 5s in total. Does not take advantage of concurrent programming


import asyncio
import time
async def visit_url(url, response_time):
  """ Visit  url"""
  await asyncio.sleep(response_time)
  return f" Visit {url},  The return result has been obtained "

async def run_task():
  """ Collect subtasks """
  task = visit_url('http://wangzhen.com', 2)
  task_2 = visit_url('http://another', 3)
  await asyncio.run(task)
  await asyncio.run(task_2)
asyncio.run(run_task())
print(f" Time elapsed: {time.perf_counter() - start_time}")

3. If it is concurrent programming, this program only needs to consume the waiting time of 3s, that is, task2.

To use concurrent programming, you need to change the above code by 1. asyncio. gather creates two subtasks, and when await occurs, the program schedules between these two subtasks.


async def run_task():
  """ Collect subtasks """
  task = visit_url('http://wangzhen.com', 2)
  task_2 = visit_url('http://another', 3)
  await asynicio.gather(task1, task2)

Instance extension:


import asyncio
from threading import Thread
 
 
async def production_task():
  i = 0
  while True:
    #  Will consumption This program registers every second 1 To a loop running in a thread, thread_loop Will get every second 1 A 1 Direct printing i Infinite loop task of 
    asyncio.run_coroutine_threadsafe(consumption(i),
                     thread_loop) #  Note: run_coroutine_threadsafe  This method can only be used for loop events running in threads 
    await asyncio.sleep(1) #  Must be added await
    i += 1
 
 
async def consumption(i):
  while True:
    print(" I am the first {} Mission ".format(i))
    await asyncio.sleep(1)
 
 
def start_loop(loop):
  #  Run the event loop,  loop Pass it in as parameters to run 
  asyncio.set_event_loop(loop)
  loop.run_forever()
 
 
thread_loop = asyncio.new_event_loop() #  Get 1 Event loops 
run_loop_thread = Thread(target=start_loop, args=(thread_loop,)) #  Loop the secondary event in the 1 Prevent blocking the current main thread 
run_loop_thread.start() #  Runs the thread, and the co-programmed event loop also runs 
 
advocate_loop = asyncio.get_event_loop() #  Register production task schedules in this loop 
advocate_loop.run_until_complete(production_task()) #  Run the secondary loop 

Related articles: