How does python implement asynchronous call function execution

  • 2021-07-10 20:12:55
  • OfStack

Before implementing asynchronous invocation, what are synchronous invocation and asynchronous invocation

Synchronization: Refers to the logic of completing the transaction. Execute the first transaction first. If it is blocked, it will wait until the transaction is completed, and then execute the second transaction in sequence
Asynchronous: Is relative to synchronization, asynchronous refers to in the process of invoking this transaction, will not wait for the transaction processing results, directly deal with the second transaction, through the status, notification, callback to inform the caller processing results

Under Analysis 1, the following example:

A decorator async and two function functions A and B are defined

sleep 10s inside A, then print a function string

Print b function string directly in B

We call two functions in sequence:

A ()

B( )

Since the function A is sleeping and we don't want the program to be blocked in the sleeping state of the function A, we use asynchronous execution, that is, in the sleeping state of the function A, so that other tasks can be executed


from threading import Thread
from time import sleep


def async(f):
  def wrapper(*args, **kwargs):
    thr = Thread(target=f, args=args, kwargs=kwargs)
    thr.start()

  return wrapper


@async
def A():
  sleep(10)
  print(" Function A Be asleep 10 Seconds. . . . . . ")
  print("a function")


def B():
  print("b function")


A()
B()

Implementation results:


#b function
# Function A Be asleep 10 Seconds. . . . . . 
#a function

Related articles: