Introduction to Advanced Python

Async-Await

Dec 2024
@1995parham
python-logo

Threading

In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.

Thread

The Thread class represents an activity that is run in a separate thread of control.

<Code Time.py>

Flask in single thread and multi-thread modes

Multi-Threading Flask


    app.run(threaded=True)
    

Threading in action


    import threading


    def run():
        print('some works')


    threading.Thread(target=run).start()
    
code thread.py

Thread.join(timeout=None)

Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.

Lock

A primitive lock is a synchronization primitive that is not owned by a particular thread when locked.

Locks also support the context management protocol.


    with lck:
        # some awesome synchronized works
    

Generators

Generators functions allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.


    def firstn(n):
        sum = 0
        while num < n:
            yield num
            num += 1


    for i in firstn(10):
        print(i)
    
code generators.py

<Code Time.py>

Let's write fibonacci with generators.

Async-Await

The newer and cleaner syntax is to use the async/await keywords. Introduced in Python 3.5, async is used to declare a function as a coroutine. It can be applied to the function by putting it at the front of the definition.

Async-Await (cont'd)


    async def ping_server():
        # ping code here

    async def ping_local():
        return await ping_server('127.0.0.1')
    

Running the event loop

None of the coroutine stuff will matter (or work) if you don't know how to start and run an event loop.

The event loop is the central point of execution for asynchronous functions

Running the event loop (cont'd)


    loop = asyncio.get_event_loop() 
    loop.run_until_complete(speak_async())
    loop.close()
    
Fork me on GitHub