Threading Examples
Here are some examples of using thread to run code in sub threads.
General usage
Here are the most common ways to spawn threads.
On-Demand Threads
These threads are created on runtime and are not started automatically.
Calling thread.Thread.start()
will start the thread immediately.
import time
import thread
def my_background_task():
time.wait(5)
print('My background task is complete.')
worker = thread.Thread(target=my_background_task)
worker.start()
print('Started background task.')
worker.join() # Halt the main thread until the background thread finishes.
# Terminal output:
# > Started background task.
# > My background task is complete.
Decoratored Functions
Decoratored functions automatically spawn new threads and run in the background everytime they are called,
simply use thread.threaded
to decorate the function.
import time
import thread
@thread.threaded
def my_background_task():
time.wait(5)
print('My background task is complete.')
worker = my_background_task()
print('Started background task.')
worker.join()
# Terminal output:
# > Started background task.
# > My background task is complete.
Type Safety
Thread supports type annotations for Python 3.9+. This will help your LSP to detect type errors and reduce the risk of runtime errors.
A Simple Example
All that is needed is to annotate the function like you would in Python.
import thread
def background_function(x: int) -> int:
return x + 1
worker = Thread(target=background_function, args=(5,))
worker.start()
returned = worker.get_return_value() # int