线程
线程是可以独立处理和管理的最小计算单元。线程用于将程序分解为可以同时运行的计算部分。线程会乱序执行
多处理器 并行
多线程 并发
进程
使用进程时上下文切换成本更高
线程的基本异步编程
from threading import Thread
from time import sleep
from typing import Optional
class ExampleThread(Thread):
def __init__(self, seconds: int, name: str) -> None:
super().__init__()
self.seconds: int = seconds
self.name: str = name
self._return: Optional[int] = None
def run(self) -> None:
print(f"thread {self.name} is running")
sleep(self.seconds)
print(f"thread {self.name} has finished")
self._return = self.seconds
def join(self) -> int:
Thread.join(self)
return self._return
one: 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 running
thread two is running
thread three is running
we have started all of our threads
thread one has finished
thread three has finished
thread two has finished
5.005641937255859 has elapsed
5
5
5