多进程
多进程2
1 import time 2 from multiprocessing import Process 3 import os 4 5 6 def dance(num, name): 7 print('Process of basketball is %s.' % os.getpid()) 8 for i in range(num): 9 print(name+' is playing basketball right now.') 10 time.sleep(0.5) 11 12 13 def sing(num, name): 14 print('Process of the guitar is %s.' % os.getpid()) 15 for i in range(num): 16 print(name+' is playing the guitar next door.') 17 time.sleep(0.5) 18 19 20 if __name__ == '__main__': 21 print('Parent process: %s.' % os.getpid()) 22 # 下面这两个是在创建子进程对象并指定执行的任务名 23 # target就是指定函数名,args就是参数 24 # 若使用元组,参数位置必须按照定义的函数的顺序来写 25 p = Process(target=dance, args=(2, 'Bob')) # 只传一个参数时,加个逗号,否则解释器会认为这不是一个元祖而是一个数字 26 f = Process(target=sing, kwargs={'num': 2, 'name': 'Eric'}) # 使用字典时,甚至可以不按顺序,只要参数名称对就可以 27 # 启动子进程并执行任务 28 p.start() 29 f.start() 30 p.join() 31 f.join() 32 print('Boys love these things.')