進程:html
from multiprocessing import Process from threading import Thread def get(lis): while len(lis) != 0: # 注意必定要加上斷定條件,否則進程不會退出的。 s = lis.pop() print('get %s', s) if __name__ == '__main__': lis = list(range(1, 11)) process1 = Process(target=get, args=(lis,)) process2 = Process(target=get, args=(lis,)) process1.start() process2.start() process1.join() get %s 10 get %s 10 get %s 9 get %s 9 get %s 8 get %s 8 get %s 7 get %s 7 get %s 6 get %s 6 get %s 5 get %s 4 get %s 5 get %s 3 get %s 4 get %s 2 get %s 3 get %s 1 get %s 2 get %s 1
線程:python
from multiprocessing import Process from threading import Thread def get(lis): while len(lis) !=0: # 注意必定要加斷定條件,否則線程不會會一直等待,不會退出的。 s = lis.pop() print('get %s', s) if __name__ == '__main__': lis = list(range(1, 11)) thread1 = Thread(target=get, args=(lis,)) thread2 = Thread(target=get, args=(lis,)) thread1.start() thread2.start() thread1.join() thread2.join() print('finished') get %s 10 get %s 9 get %s 8 get %s 7 get %s 6 get %s 5 get %s 4 get %s 3 get %s 2 get %s 1 finished
from queue import Queue多線程
from multiprocessing import Queuepost
from multiprocessing import Manager性能
queue = Manager().Queue()url
from multiprocessing import Pipespa
from multiprocessing import manager線程
manager = manager()code
my_list = manager.list() / my_dict = manager.dict()/htm
在使用Queue的時候,若是使用的默認的get後者put方法,(即(block=True, timeout=None))無論是多線程,仍是多進程,在從隊列中取出url的時候必定要加上斷定條件,while queue.qsize()!=0 或者 while not queue.empty(),否則進程或者線程會一直等待。
from multiprocessing import Process, Pipe def producer(queue): queue.send('bobby') def comsumer(queue): print(queue.recv()) if __name__ == '__main__': recv_pipe, send_pipe = Pipe() 注意建立時候必須同時建立兩個對象一個用於發送一個用於取出。 my_producer = Process(target=producer, args=(send_pipe,)) my_comsumer = Process(target=comsumer, args=(recv_pipe,)) my_producer.start() my_comsumer.start() my_producer.join() my_comsumer.join() 輸出: bobby