Python Revisited Day10 (进程与线程)
《Python 3 程序开发指南》学习笔记
有俩种方法可以对工作载荷进行分布,一种是使用多进程,另一种是使用多线程。
10.1 使用多进程模块
我们可以使用Python的subprocess模块来实现这一需求,改模块提供了运行其他程序的功能,可以传递我们需要的任意命令行参数,并且,如果需要,还可以使用管道在其中进行通信。
#maincontrol.py
import subprocess
import os, sys
def main():
child = os.path.join(os.path.dirname(__file__),
"subcontrol.py")
pipes = []
s = "See you again, Robot {0}"
for i in range(10):
command = [sys.executable, child]
pipe = subprocess.Popen(command, stdin=subprocess.PIPE)
pipes.append(pipe)
pipe.stdin.write(s.format(i).encode("utf-8") + b"\n") #subprocess模块读写的是字节,而并不是字符串
pipe.stdin.close()
while pipes:
print("?????")
pipe = pipes.pop()
pipe.wait()
print("#####")
if __name__ == "__main__":
main()
#subcontrol.py
import sys
sys.stdin = sys.stdin.detach()
stdin = sys.stdin.read()
lines = stdin.decode("utf8", "ignore")
print(lines)
或者
#subcontrol.py
import sys
stdin = sys.stdin.buffer.read()
lines = stdin.decode("utf8", "ignore")
print(lines)
输出为:
?????
See you again, Robot 0
See you again, Robot 3
See you again, Robot 1
See you again, Robot 7
See you again, Robot 6
See you again, Robot 9
See you again, Robot 5
See you again, Robot 8
See you again, Robot 2
#####
?????
#####
?????
#####
?????
#####
?????
#####
?????
See you again, Robot 4
#####
?????
#####
?????
#####
?????
#####
?????
#####
可以发现,先创建的进程不一定能够先完成。
10.2 将工作分布到多个线程
多个线程共享数据的时候,可能会发生另个现成对现有的数据进行了不当的修改,常见的解决的方案是使用某种锁机制。通过将共享数据的存取劝降限定在锁的作用范围之内,可以保证共享数据在同一个时刻只能由一个线程进行存取,即便这种保护不是直接的。
锁机制存在的一个问题是存在死锁的风险。比如,thread#1请求锁A并在此基础上请求锁B,但是thread#1不能锁B,因为此时thread#2以及锁B,只有当thread#2解锁B,thread#1才能锁B,万一不巧,这个时候thread#2也请求锁B,那么就会发生死锁,俩个线程都被阻塞。
线程的内容就看了一下, threading模块:
here
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix