day10-进程
一、进程
1 # IO操作(socket)不占用CPU,宜用多线程,计算占用CPU,宜用多进程 2 # 进程没有GIL锁,而且不存在锁的概念 3 from multiprocessing import Process 4 import threading 5 import os 6 7 8 def thead_run(): 9 # 返回线程标识符 10 print(":{0}".format(threading._get_ident())) 11 12 13 def info(title): 14 print(title) 15 print('module name:', __name__) 16 # 父进程id, python2 linux可用 17 # print('parent process', os.getppid()) 18 # 子进程id 19 print('process id:', os.getpid()) 20 # 进程中嵌入线程 21 t = threading.Thread(target=thead_run, args=()) 22 t.start() 23 print("\n\n") 24 25 26 def f(name): 27 info('\033[31;1mfunction f\033[0m') 28 print('hello', name) 29 30 if __name__ == '__main__': 31 p_obj_list = list() 32 # 父进程 33 info('\033[32;1mmain process line\033[0m') 34 for i in range(5): 35 # 启动多个子进程 36 p = Process(target=f, args=('bob',)) 37 p.start() 38 p_obj_list.append(p) 39 # 等待进程结果 40 for p in p_obj_list: 41 p.join()
二、进程Queue
1 # 线程Queue 2 import Queue, threading 3 4 def f(): 5 q.put([42, None, 'hello']) 6 7 if __name__ == '__main__': 8 q = Queue.Queue() 9 p = threading.Thread(target=f, args=()) 10 p.start() 11 # 线程数据共享,可以取到值 12 print(q.get()) 13 p.join() 14 15 # 进程Queue 16 from multiprocessing import Process, Queue 17 18 19 def f2(q2): 20 q2.put([42, None, 'hello']) 21 22 if __name__ == '__main__': 23 q2 = Queue() 24 # 实际是克隆一份Queue,中间件会序列化这份Queue, 25 # 然后把新数据反序列化还回主进程,并不是真的数据共享 26 p = Process(target=f2, args=(q2, )) 27 p.start() 28 # 线程数据共享,可以取到值 29 print(q2.get()) 30 p.join()

浙公网安备 33010602011771号