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.
The Thread class represents an activity that is run in a separate thread of control.
Flask in single thread and multi-thread modes
app.run(threaded=True)
import threading
def run():
print('some works')
threading.Thread(target=run).start()
code thread.pyWait 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.
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 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.pyLet's write fibonacci with generators.
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 def ping_server():
# ping code here
async def ping_local():
return await ping_server('127.0.0.1')
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
loop = asyncio.get_event_loop()
loop.run_until_complete(speak_async())
loop.close()