1 #上节多线程内容回顾 2 3 4 进程 至少包含一个 线程 5 6 线程 内存共享 7 线程同时修改同一份数据时必须加锁,mutex互斥锁 8 递归锁 9 join 等待一个线程结束10 11 #串行12 def run():13 print ('run thread...')14 15 for i in range(10): #串行16 t = threading.Thread(target=run,args=(n,))17 t.start()18 t.join()19 20 21 #并行方法22 def run():23 print ('run thread...')24 25 t_res = []26 27 for i in range(10): 28 t = threading.Thread(target=run,args=(n,))29 t.start()30 t_res.append(t)31 32 for r in t_res:33 r.join()34 35 36 37 守护线程(slave) 服务于非守护线程(master)38 39 40 #守护线程41 def run():42 print ('run thread...')43 44 for i in range(10): 45 t = threading.Thread(target=run,args=(n,))46 t.setDaemon(True)47 t.start()48 49 print ('master is done...')50 51 52 53 queue队列54 解耦,使程序直接实现松耦合,55 提高处理效率,56 57 FIFO = first in first out 先进先出58 LIFO = last in first out 后进先出59 60
1 #多线程的使用场景 #多进程的基本使用 2 3 4 #io 操作不占用CPU (读取数据) 5 6 #计算占用CPU , 1+1 7 8 #python的多线程,不适合CPU密集操作型的任务,适合IO操作密集型的任务 9 10 '''11 import multiprocessing12 import time13 14 from multiprocessing import Process15 16 def f(name):17 time.sleep(2)18 print('hello', name)19 20 if __name__ == '__main__':21 p = Process(target=f, args=('bob',))22 p.start()23 p.join()24 25 '''26 27 28 29 '''30 import multiprocessing31 import time32 33 def run(name):34 time.sleep(2)35 print('hello', name)36 37 if __name__ == '__main__':38 for i in range(10):39 p = multiprocessing.Process(target=run, args=('bob %s' %i,))40 p.start()41 42 43 '''44 '''45 import multiprocessing46 import time47 import threading48 49 def thread_run():50 print (threading.get_ident())51 def run(name):52 time.sleep(2)53 print('hello', name)54 t = threading.Thread(target=thread_run,)55 t.start()56 57 if __name__ == '__main__':58 for i in range(10):59 p = multiprocessing.Process(target=run, args=('bob %s' %i,))60 p.start()61 62 '''
1 #get 进程ID 2 3 from multiprocessing import Process 4 import os 5 6 def info(title): 7 print(title) 8 print('module name:', __name__) 9 print('parent process:', os.getppid())10 print('process id:', os.getpid())11 print("\n\n")12 13 def f(name):14 info('1mcalled from child process function f')15 print('hello', name)16 17 if __name__ == '__main__':18 info('1mmain process line')19 p = Process(target=f, args=('bob',))20 p.start()21 p.join()
1 #进程间数据交互#进程同步#进程池的使用 (信号量) 2 3 #进程间通讯 4 #不同进程间内存是不共享的,要想实现两个进程间的数据交换,可以用以下方法: 5 6 #Queues使用方法跟threading里的queue差不多 7 8 ''' 9 #Queues 使用方法跟threading里的queue差不多 10 from multiprocessing import Process, Queue 11 12 def f(q): 13 q.put([42, None, 'hello']) 14 15 if __name__ == '__main__': 16 q = Queue() 17 p = Process(target=f, args=(q,)) 18 p.start() 19 print(q.get()) # prints "[42, None, 'hello']" 20 p.join() 21 22 ''' 23 24 25 26 ''' 27 #Pipes方法 28 29 from multiprocessing import Process, Pipe 30 31 def f(conn): 32 conn.send([42, None, 'hello']) 33 conn.close() 34 35 if __name__ == '__main__': 36 parent_conn, child_conn = Pipe() 37 p = Process(target=f, args=(child_conn,)) 38 p.start() 39 print(parent_conn.recv()) # prints "[42, None, 'hello']" 40 p.join() 41 42 ''' 43 ''' 44 #Managers方法 默认加锁 45 46 from multiprocessing import Process, Manager 47 import os 48 49 50 def f(d, l): 51 d[1] = '1' 52 d['2'] = 2 53 d[0.25] = None 54 l.append(os.getpid()) 55 print(l) 56 57 if __name__ == '__main__': 58 with Manager() as manager: 59 d = manager.dict()#生成一个字典,可在多个进程间共享和传递 60 l = manager.list(range(5))#生成一个列表,可在多个进程间共享和传递 61 p_list = [] #用来存放等待全部进程的列表 62 for i in range(10): 63 p = Process(target=f, args=(d, l)) 64 p.start() 65 p_list.append(p) 66 for res in p_list:#等待结果 67 res.join() 68 69 print(d) 70 print(l) 71 ''' 72 ''' 73 #Managers方法 默认加锁 74 75 from multiprocessing import Process, Manager 76 import os 77 78 def f(d, l): 79 d[os.getpid()] = os.getpid() 80 l.append(os.getpid()) 81 print(l) 82 83 if __name__ == '__main__': 84 with Manager() as manager: 85 d = manager.dict()#生成一个字典,可在多个进程间共享和传递 86 l = manager.list(range(5))#生成一个列表,可在多个进程间共享和传递 87 p_list = [] #用来存放等待全部进程的列表 88 for i in range(10): 89 p = Process(target=f, args=(d, l)) 90 p.start() 91 p_list.append(p) 92 for res in p_list:#等待结果 93 res.join() 94 95 print(d) 96 print(l) 97 ''' 98 ''' 99 #进程同步100 101 from multiprocessing import Process, Lock102 103 def f(l, i): #锁,值104 #l.acquire()105 print('hello world', i)106 #l.release()107 108 if __name__ == '__main__':109 lock = Lock()110 for num in range(10):111 Process(target=f, args=(lock, num)).start()112 113 '''114 '''115 116 from multiprocessing import Process, Lock117 118 def f(l, i): #锁,值119 l.acquire()120 try:121 print('hello world', i)122 finally:123 l.release()124 125 if __name__ == '__main__':126 lock = Lock()127 128 for num in range(10):129 Process(target=f, args=(lock, num)).start()130 131 '''132 133 #进程池的使用 (信号量)134 135 #进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,136 # 如果进程池序列中没有可供使用的进进程,那么程序就会等待,137 # 直到进程池中有可用进程为止。138 # 进程池中有两个方法:139 #apply #串行140 #apply_async #并行141 142 '''143 144 from multiprocessing import Process,Pool145 import time146 147 def Foo(i):148 time.sleep(2)149 return i+100150 151 def Bar(arg):152 print('-->exec done:',arg)153 154 pool = Pool(5)155 156 for i in range(10):157 pool.apply_async(func=Foo, args=(i,),callback=Bar)158 #pool.apply(func=Foo, args=(i,))159 160 print('end')161 pool.close()162 pool.join()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。163 164 '''165 166 from multiprocessing import Process,Pool,freeze_support167 import time168 import os169 170 def Foo(i):171 time.sleep(2)172 print('in process',os.getpid())173 return i + 100174 175 def Bar(arg):176 print('-->exec done:',arg,os.getpid())177 178 if __name__ =='__main__':179 #freeze_support()180 pool = Pool(processes=3) #允许进程池同时放入5个进程181 print ('主进程',os.getpid())182 for i in range(10):183 pool.apply_async(func=Foo, args=(i,),callback=Bar)#callback回调184 #pool.apply(func=Foo, args=(i,))#串行185 #pool.apply_async(func=Foo, args=(i,))#并行186 187 print('end')188 pool.close()#一定要先关闭进程池再join()189 pool.join()#进程池中进程执行完毕后再关闭,如果注释pool.join(),那么程序直接关闭。