zoukankan      html  css  js  c++  java
  • 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"
    ") #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

  • 相关阅读:
    微信开发第一步—接入指南
    摸不着
    dubbo监控中心安装部署
    解决mapper映射文件不发布问题
    单例设计模式
    Spring与Hibernate集成、Spring与Struts2集成
    Spring MVC对日期处理的不友好问题
    常用的系统存储过程
    这就是成长(刚开始经常犯的错误随记)
    一些简单的查询
  • 原文地址:https://www.cnblogs.com/MTandHJ/p/11225812.html
Copyright © 2011-2022 走看看