2018-04-02

python高级

多线程通讯

队列 Queue---来完成多进程间的数据传递

#引进相对应的模块
from multiprocessing import Process,Queue
#引进时间模块
import time

def send(q):
    
    print("发送数据的子进程 " )
    #像对列中添加一条数据
    q.put("我是你爸爸~~~")
    #时间间隔为一秒
    time.sleep(1)
        
def revice(q):
    
    print("接收数据的子进程")
    #从队列中获取数据
    d = q.get()
    print("接收的数据-->%s" % d)
    #时间间隔为一秒
    time.sleep(1)
        
if __name__ == "__main__":
    #定义队列变量
    q = Queue()
    
    t1 = Process(target=send, args = [q,],name = "sendd")
    t1.start()
    
    t2 = Process(target=revice,args = [q,],name = "reviced")
    t2.start()
    

管道 Pipe---方式单一

#引进相对应的方法模块
from multiprocessing import Process,Pipe
#引进时间模块
import time


def send(q):
    print("发送数据的子进程 ")
    # 像对列中添加一条数据
    q.send("我是你爸爸~~~")
    q.close()
    # 时间间隔为一秒
    time.sleep(1)


def revice(q):
    print("接收数据的子进程")
    # 从队列中获取数据
    d = q.recv()
    print("接收的数据-->%s" % d)
    # 时间间隔为一秒
    time.sleep(1)


if __name__ == "__main__":
    #接受返回的元组
    (parent_pipe,son_pipe) = Pipe()
    
    t1 = Process(target=send, args=(son_pipe,), name="sendd")
    t1.start()
    
    t2 = Process(target=revice, args=(parent_pipe,), name="reviced")
    t2.start()

管理器 Manager---数据共享

#应用相对应的模块
from multiprocessing import Process,Manager
#引用时间模块
#import time

def send(list,dict):
    list.append("老刘")
    list.append("老张")
    list.append("老李")
    dict["name"] = "梅前途"
    dict["age"] = "20"
    dict["gender"] = "男"
    
    print(list)
    print(dict)
    
if __name__ == "__main__":

    with Manager() as manager:
        #获取一个列表
        list = manager.list()
        #获取一个字典
        dict = manager.dict()
        
        ls = []
        
        for x in range(10):
            task = Process(target = send, args = (list,dict))
            task.start()
            
            ls.append(task)
        
        for x in ls:
            x.join()

模拟上传下载

#引入分隔模块
from multiprocessing import Process
#引入时间模块
import time
#引入时间模块
import os


def download(path):
    print("开始下载~~~")
    for x in range(5):
        print("正在下载中%s~~~" % path)
        print(os.getpid())
        print(os.getppid())
        time.sleep(1)
    print("下载结束")
    
def printMsg(msg):
    print("开始打印~~~")
    for x in range(5):
        print("正在打印中%s" % msg)
        print(os.getpid())
        print(os.getppid())
        time.sleep(1)
        
    print("打印结束")
    
if __name__ == "__main__":
    #启动的时间
    start_time = time.time()
    
    t1 = Process(target = download, args = ("www.yellow.com",), name = "download")
    #启动下载
    t1.start()
    
    t2 = Process(target= printMsg, args = ("刘国营是个大帅哥",), name = "peintMsg")
    #启动打印
    t2.start()
    
    print("程序结束", time.time() - start_time)
    

你可能感兴趣的:(2018-04-02)