SoFunction
Updated on 2024-10-29

Python implementation code for handling concurrency using the asyncio package

Handling concurrency with the asyncio package

The asyncio package: concurrency using event loop-driven concurrency.

Threads vs. Co-Threads

'\ thinking' rotating waiting effect

In [1]: import threading
 
In [2]: import itertools
 
In [3]: import time,sys
 
In [4]: class Signal:  # Define a simple mutable object; go attribute Controls the thread from the outside
   ...:     go = True
 
In [5]: def spin(msg,signal):
   ...:     w,flush = ,
   ...:     for char in ('|/-\\'):  # Iterative generation of elements from sequences
   ...:         status = char + ' ' + msg
   ...:         w(status)
   ...:         flush()
   ...:         w('\x08' * len(status))  # Backspace: the trick to \x08 text animation
   ...:         (1)
   ...:         if not :
   ...:             break
   ...:     w(' ' * len(status) + '\x08' * len(status))
 
In [6]: def slow():
   ...:     (3)
   ...:     return 42
 
In [9]: def super():
   ...:     signal = Signal()
   ...:     sp = (target=spin,args=('thinking',signal))
   ...:     print('============')
   ...:     ()
   ...:     res = slow()
   ...:      = False
   ...:     ()
   ...:     return res

Note: Python does not provide an API for terminating threads, this is intentional. To close a thread, you must send a message to the thread. Properties are used here. The clean rule of exit.

Concurrent programs for the asyncio API:

1 Definition bodies must be usedyield from and can't be usedyield

2 The concatenation is to be driven by the caller and passed by the caller through theyield from invocations

3 Or pass the concatenation to one of the functions in the asyncio package, e.g. ()

4 @ Decorators should be used for co-processing

asyncio implementation of animation effects

In [1]: import asyncio
 
In [3]: import itertools
 
In [4]: import sys
 
# Concurrent programs handed off to asyncio need to be decorated with this decorator. This is not mandatory, but highly recommended.
In [5]: @
   ...: def spin(msg):  # No multi-threaded shutdown parameters
   ...:     w,flush = , 
   ...:     for char in ('|/-\\'):
   ...:         status = char + ' ' + msg
   ...:         w(status)
   ...:         flush()
   ...:         w('\x08' * len(status))
   ...:         try:
   ...:             yield from (.1)  # Doesn't block the event loop
                # After spin function wakes up, cancel request exception, exit loop
   ...:         except :
   ...:             break
   ...:     write(' ' * len(status) + '\x08' * len(status))
   ...:
 
In [6]: @
   ...: def slow():
            # Hand over control to the main loop and end this co-program when sleep is over
   ...:     yield from (3)
   ...:     return 42
   ...:
 
In [9]: @
   ...: def sup():
            # asyncio schedules the runtime of the spin coprocess, encapsulated in a Task object sp
   ...:     sp = (spin('thinking!'))
   ...:     print('spin obj:',sp)
            # sup is also a coprocessor, so you can drive slow() with yield from
   ...:     res = yield from slow()
            ()
   ...:     return res
   ...:
 
In [10]: def main():
    ...:     loop = asyncio.get_event_loop()
    ...:     res = loop.run_until_complete(sup())
    ...:     ()
    ...:     print('answer:',res)
    ...:
 
In [11]: main()
D:\python36\Scripts\ipython:3: DeprecationWarning: () function is deprecated, use ensure_future()
spin obj: <Task pending coro=<spin() running at <ipython-input-5-0304845f34e1>:1>>
answer: 42!

Do not use () in an asyncio thread unless you want to block the main thread, thereby freezing the event loop or the entire application. You should use yield from () if you need to do nothing for a certain period of time.

@ decorator is not mandatory, but it is highly recommended, as it allows the

1 Bringing out the co-programming helps with debugging.

2 If the concatenation is garbage-collected before it has produced a value (implying that there is an operation that has not been completed, and therefore possibly a defect), then a warning can be issued.

3 This decorator does not pre-excite co-processes.

to this article on the use of Python asyncio package to deal with concurrency of the implementation of the code of the article is introduced to this, more related to Python asyncio package content, please search for my previous articles or continue to browse the following related articles I hope that you will support me in the future more!