1. 程式人生 > >python3學習筆記(三)多線程與多進程

python3學習筆記(三)多線程與多進程

ttr pid make start lee close gif 自己 oops

線程thread,庫threading

進程process,庫Process

使用起來方法跟其他語言相似,也不需要下載其他的庫,語言自帶的庫裏就有

1.多線程的例子

技術分享圖片
 1 #coding=utf-8
 2 import threading
 3 from time import sleep, ctime
 4 
 5 loops = [1, 2]
 6 
 7 def loop(nloop, nsec):
 8     print(start loop, nloop, at:, ctime())
 9     sleep(nsec)
10     print(loop, nloop, 
done at:, ctime()) 11 12 13 14 def main(): 15 print(starting at:, ctime()) 16 threads = [] 17 nloops = range(len(loops)) # nloops=1,2 18 19 for i in nloops: 20 t = threading.Thread(target=loop, args=(i, loops[i])) 21 threads.append(t) 22 23 for i in nloops:
24 threads[i].start() 25 26 for i in nloops: 27 threads[i].join() 28 29 print(all end, ctime()) 30 31 32 if __name__ == __main__: #Make a script both importable and executable 33 main()
View Code

2.多進程的例子

技術分享圖片
 1 #coding=utf-8
 2 from multiprocessing import  Process
3 import os 4 5 def info(title): 6 print(title) 7 print(module name:, __name__) 8 if hasattr(os, getppid): 9 print(parent process:, os.getppid()) #父進程id 10 print(process id:, os.getpid()) #進程自己的id 11 12 13 def f(name): 14 info(function f) 15 print(hello, name) 16 17 #如果本進程A創建了一個進程B 那麽B是A的子進程 A是B的父進程 18 if __name__ == __main__: 19 info(main process) 20 p = Process(target=f, args=(ks, )) 21 p.start() 22 p.join()
View Code

python3學習筆記(三)多線程與多進程