这将是多线一个系列,一个关于进程、程编程初线程和 协程的体验系列。 主要用于:回顾和复习以往所学的多线知识 以及 希望这点经验能够帮助正在学习编程的你 创建文件 0809.py 在第一个终端窗口中执行 在第二个终端窗口中执行 你会发现其进程ID也是 3344和线程ID一致。这是程编程初因为Linux中规定,当一个进程中只有一个线程的体验情况下,云服务器线程ID等于进程ID。多线或则说,程编程初进程的体验第一个线程(主线程)的ID等于进程ID。 执行命令 python 0809.py 可以发现,两个线程并非严格交替执行,体验而是多线随机执行。 我们再来查看一下相关的云南idc服务商程编程初进程和线程 可以看出该进程中有三个线程,分别是体验主线程 3784 和两个子线程 3785(producer)、3786(consumer) 今天我们就先讲到这里,重点掌握: 1、如何在python代码中和shell终端中查看线程id 进程ID 以及进程中包含的线程。 2、理解生产/消费者模型,因为这个模型会在接下来的学习中被多次提到 前言
查看线程ID
经典的多线生产者/消费者模型(也有人称之为,发布/订阅模型)
# 0809.py import time import threading count = 0 def consumer(): global count while True: if count <= 0: continue count = count - 1 print(fcount is { count},程编程初 consumer thread id is { threading.get_native_id()}) time.sleep(2) def producer(): global count while True: count = count + 1 print(fcount is { count}, producer thread id is { threading.get_native_id()}) time.sleep(1) if __name__ == __main__: tp = threading.Thread(target=producer) tc = threading.Thread(target=consumer) tp.start() tc.start()