ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

Python Revisited Day10 (进程与线程)

2019-07-22 14:55:35  阅读:274  来源: 互联网

标签:again Python stdin Robot sys See 线程 Revisited #####


目录

《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

#####
?????
#####
?????
#####
?????
#####
?????
#####

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

subprocess模块学习

10.2 将工作分布到多个线程

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

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

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

标签:again,Python,stdin,Robot,sys,See,线程,Revisited,#####
来源: https://www.cnblogs.com/MTandHJ/p/11225812.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有