线程
线程是可以独立处理和管理的最小计算单元。线程用于将程序分解为可以同时运行的计算部分。线程会乱序执行


多处理器 并行
多线程 并发
进程
使用进程时上下文切换成本更高

线程的基本异步编程

from threading import Threadfrom time import sleepfrom typing import Optionalclass ExampleThread(Thread):def __init__(self, seconds: int, name: str) -> None:super().__init__()self.seconds: int = secondsself.name: str = nameself._return: Optional[int] = Nonedef run(self) -> None:print(f"thread {self.name} is running")sleep(self.seconds)print(f"thread {self.name} has finished")self._return = self.secondsdef join(self) -> int:Thread.join(self)return self._returnone: ExampleThread = ExampleThread(seconds=5, name="one")two: ExampleThread = ExampleThread(seconds=5, name="two")three: ExampleThread = ExampleThread(seconds=5, name="three")start = time.time()one.start()two.start()three.start()print("we have started all of our threads")one_result = one.join()two_result = two.join()three_result = three.join()finish = time.time()print(f"{finish - start} has elapsed")print(one_result)print(two_result)print(three_result)
thread one is runningthread two is runningthread three is runningwe have started all of our threadsthread one has finishedthread three has finishedthread two has finished5.005641937255859 has elapsed555
