目录
《Python 3 程序开发指南》学习笔记
有俩种方法可以对工作载荷进行分布,一种是使用多进程,另一种是使用多线程。
10.1 使用多进程模块
我们可以使用Python的subprocess模块来实现这一需求,改模块提供了运行其他程序的功能,可以传递我们需要的任意命令行参数,并且,如果需要,还可以使用管道在其中进行通信。
#maincontrol.py
import subprocess
import os, sysdef 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.pyimport syssys.stdin = sys.stdin.detach()
stdin = sys.stdin.read()
lines = stdin.decode("utf8", "ignore")
print(lines)
或者
#subcontrol.py
import sysstdin = sys.stdin.buffer.read()
lines = stdin.decode("utf8", "ignore")
print(lines)
输出为:
?????
See you again, Robot 0See you again, Robot 3See you again, Robot 1See you again, Robot 7See you again, Robot 6See you again, Robot 9See you again, Robot 5See you again, Robot 8See 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模块: