多线程和多进程

多线程:

两种方法:

其一:

使用threading.Thread()方法

  1. # coding=utf-8  
  2. import threading  
  3. import time  
  4. def hello():  
  5.     for i in range(2):  
  6.         print("hello",time.ctime())  
  7.         time.sleep(1)  
  8. def hi():  
  9.     for i in range(2):  
  10.         print("hi",time.ctime())  
  11.         time.sleep(2)  
  12.     
  13. t1=threading.Thread(target=hello)  
  14. t2 = threading.Thread(target=hi)  
  15. t1.start()  
  16. t2.start()  
  17. print("end")  

结果如下:

hello Mon Nov 6 13:53:34 2017

hi Mon Nov 6 13:53:34 2017

end

hello Mon Nov 6 13:53:35 2017

hi Mon Nov 6 13:53:36 2017

 

看到主线程先执行完了,修改成所有子线程执行完再执行主线程

  1. t1=threading.Thread(target=hello,name="线程一")  
  2. t2 = threading.Thread(target=hi,name="线程二")  
  3. for th in [t1,t2]:  
  4.     th.start()  
  5.     th.join()  
  6. print("end")  

now 当主线程执行完之后,结束子线程

  1. t1=threading.Thread(target=hello,name="线程一")  
  2. t2 = threading.Thread(target=hi,name="线程二")  
  3. for th in [t1,t2]:  
  4.     th.setDaemon(True)  
  5.     th.start()  
  6.     # th.join()  
  7. print("end")  

结果如下:

hello Mon Nov 6 14:00:05 2017

hi Mon Nov 6 14:00:05 2017

end

其二:

重写run方法:

  1. class Hi(threading.Thread):  
  2.     def run(self):  
  3.         for i in range(2):  
  4.             print("hello", time.ctime())  
  5.             print(threading.current_thread())  
  6.             time.sleep(1)  
  7. h=Hi()  
  8. h.setName("线程1")  
  9. h.start()  
  10. print(threading.current_thread())  
  11. print("end")  

结果如下:

hello Mon Nov 6 14:07:17 2017

<_MainThread(MainThread, started 5424)>

<Hi(线程1, started 9400)>

end

hello Mon Nov 6 14:07:18 2017

<Hi(线程1, started 9400)>

 

可以看到主线程的线程名是MainThread

 

 

多进程

  1. import multiprocessing  
  2. import os  
  3. def foo(name):  
  4.     print("子进程{}".format(name),os.getpid())  
  5.     
  6. if __name__ == '__main__':  
  7.     
  8.     print("主进程",os.getpid())  
  9.     p = multiprocessing.Process(target=foo,args=("进程1",))  
  10.     p.start()  
  11.     # p.join()  
  12.     print("主进程结束")  

创建进程池

 

 

  1. import multiprocessing  
  2. import os  
  3. def foo(name):  
  4.     return ("子进程{}".format(name),os.getpid())  
  5.     
  6. if __name__ == '__main__':  
  7.     
  8.     print("主进程",os.getpid())  
  9.     multiprocessing.freeze_support()  
  10.     cpus=multiprocessing.cpu_count()  
  11.     pool=multiprocessing.Pool(cpus)  
  12.     r=[]  
  13.     for i in range(cpus):  
  14.         rr=pool.apply_async(foo,args=(i,))  
  15.         r.append(rr)  
  16.     pool.close()  
  17.     pool.join()  
  18.     # p = multiprocessing.Process(target=foo,args=("进程1",))  
  19.     # p.start()  
  20.     # p.join()  
  21.     for ii in r:  
  22.         print(ii.get())  
  23.     
  24.     print("主进程结束")  
原文地址:https://www.cnblogs.com/twotigers/p/7793490.html