线程

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

并发性 - 图1并发性 - 图2

https://towardsdatascience.com/understanding-python-multithreading-and-multiprocessing-via-simulation-3f600dbbfe31

多处理器 并行

多线程 并发

进程

使用进程时上下文切换成本更高

并发性 - 图3

线程的基本异步编程

并发性 - 图4

  1. from threading import Thread
  2. from time import sleep
  3. from typing import Optional
  4. class ExampleThread(Thread):
  5. def __init__(self, seconds: int, name: str) -> None:
  6. super().__init__()
  7. self.seconds: int = seconds
  8. self.name: str = name
  9. self._return: Optional[int] = None
  10. def run(self) -> None:
  11. print(f"thread {self.name} is running")
  12. sleep(self.seconds)
  13. print(f"thread {self.name} has finished")
  14. self._return = self.seconds
  15. def join(self) -> int:
  16. Thread.join(self)
  17. return self._return
  18. one: ExampleThread = ExampleThread(seconds=5, name="one")
  19. two: ExampleThread = ExampleThread(seconds=5, name="two")
  20. three: ExampleThread = ExampleThread(seconds=5, name="three")
  21. start = time.time()
  22. one.start()
  23. two.start()
  24. three.start()
  25. print("we have started all of our threads")
  26. one_result = one.join()
  27. two_result = two.join()
  28. three_result = three.join()
  29. finish = time.time()
  30. print(f"{finish - start} has elapsed")
  31. print(one_result)
  32. print(two_result)
  33. print(three_result)
  1. thread one is running
  2. thread two is running
  3. thread three is running
  4. we have started all of our threads
  5. thread one has finished
  6. thread three has finished
  7. thread two has finished
  8. 5.005641937255859 has elapsed
  9. 5
  10. 5
  11. 5