首页 技术 正文
技术 2022年11月19日
0 收藏 317 点赞 3,646 浏览 1476 个字

目录

《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#####
?????
#####
?????
#####
?????
#####
?????
#####

可以发现,先创建的进程不一定能够先完成。

subprocess模块学习

10.2 将工作分布到多个线程

多个线程共享数据的时候,可能会发生另个现成对现有的数据进行了不当的修改,常见的解决的方案是使用某种锁机制。通过将共享数据的存取劝降限定在锁的作用范围之内,可以保证共享数据在同一个时刻只能由一个线程进行存取,即便这种保护不是直接的。

锁机制存在的一个问题是存在死锁的风险。比如,thread#1请求锁A并在此基础上请求锁B,但是thread#1不能锁B,因为此时thread#2以及锁B,只有当thread#2解锁B,thread#1才能锁B,万一不巧,这个时候thread#2也请求锁B,那么就会发生死锁,俩个线程都被阻塞。

线程的内容就看了一下, threading模块:

here

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,487
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,487
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289