Following An Intro to Threading in Python – Real Python for this one.
A thread is a separate flow of execution.
If you want tasks to run on multiple processors, you need threading. This does not mean that code runs at the same time, since this is not feasible in regular CPython.
Beispiele
- Using the threading core library:
import logging
import threading
import time
def thread_function(name):
logging.info("Thread %s: starting", name)
time.sleep(2)
logging.info("Thread %s: finishing", name)
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
logging.info("Main: Before creating thread")
x = threading.Thread(
target=thread_function,
args=(1,),
daemon=True
)
logging.info("Main: Before running thread")
x.start()
logging.info("Main: Wait for the thread to finish")
x.join() #
logging.info("Main: All done")
(This is also a nice example of python-core-logging.)
- Or using
ThreadPoolExecutor
:
import concurrent.futures
# [rest of code]
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
executor.map(thread_function, range(3))