程序與執行緒(05-08)
阿新 • • 發佈:2018-12-16
---恢復內容開始---
1.執行緒(thread)
所有的指令都是有CPU控制的,執行的,運算的。
執行緒,有時被稱為輕量程序(Lightweight Process,LWP),是程式執行流的最小單元。一個標準的執行緒由執行緒ID,當前指令 指標(PC), 暫存器集合和 堆疊組成。另外, 執行緒是程序中的一個實體,是被系統獨立排程和分派的基本單位,執行緒自己不擁有系統資源,只擁有一點兒在執行中必不可少的資源,但它可與同屬一個程序的其它執行緒共享程序所擁有的全部資源。 一個執行緒可以建立和撤消另一個執行緒An executing instance of a program is called a process.
Each process provides the resources needed to execute a program. A process has a virtual address space, executable code, open handles to system objects, a security context, a unique process identifier, (環境變數)environment variables, a priority class(優先順序), minimum and maximum working set sizes, and at least one thread of execution. Each process is started with a single thread, often called the primary thread, but can create additional threads from any of its threads.
3. 程序與執行緒的區別: 問題①:啟動一個程序快還是一個啟動一個執行緒快? 回答:啟動執行緒快。 問題②: 程序和執行緒哪個快? 回答:沒有可比性。 區別:① 執行緒共享記憶體空間,程序的記憶體是獨立的; ② 程序的執行緒之間可以直接交流;兩個程序之間交流,必須通過中間代理來實現。 ③ 建立新的執行緒很簡單,建立新程序需要對其父程序進行一次克隆。 ④ 一個執行緒可以控制和操作同一個程序裡的其他執行緒,但是程序只能操作子程序; ⑤ 修改主執行緒可能會影響子執行緒,修改父程序不會影響子程序。 4. 例項1 import threading 2 import time 3 def run(n): 4 print("task", n) 5 time.sleep(2) 6 7 t1 = threading.Thread(target=run,args=("t1",)) 8 t2 = threading.Thread(target=run,args=("t2",)) 9 10 t1.start() 11 t2.start() 12 13 #run("t1") #t1.join() 等待t1 程序完成 14 #run("t2")
5. 多執行緒案例
1 import threading 2 3 class MyThread(threading.Thread): 4 def __init__(self,n): 5 super(MyThread,self).__init__() 6 self.n = n 7 8 def run(self): 9 print("runnint task", self.n) 10 11 12 t1 = MyThread("t1") 13 t2 = MyThread("t2") 14 15 t1.start() 16 t2.start()
6. 主執行緒與子執行緒
1 import threading 2 import time 3 def run(n): 4 print("task", n, threading.current_thread(), threading.active_count()) #檢視當前執行緒是子執行緒還是主執行緒 5 time.sleep(2) 6 7 start_time = time.time() 8 t_objs = [] #列表,存執行緒例項 9 for i in range(50): 10 t = threading.Thread(target=run,args=("t-%s" %i ,)) #注意逗號不能丟 11 t.start() 12 t_objs.append(t) 13 14 for t in t_objs: 15 t.join() #等待所有的子程序結束 16 17 print("----------all threads has finished..", threading.current_thread(), threading.active_count())#活動執行緒的個數 18 print("cost:", time.time()-start_time) #計算整個程序的時間
7. 守護執行緒
不管子執行緒是否結束,主執行緒執行完程式就退出了
import threading import time def run(n): print("task", n, threading.current_thread(), threading.active_count()) #檢視當前執行緒是子執行緒還是主執行緒 time.sleep(2) start_time = time.time() t_objs = [] #列表,存執行緒例項 for i in range(50): t = threading.Thread(target=run,args=("t-%s" %i ,)) #注意逗號不能丟 t.setDaemon(True) #把當前執行緒設定為守護執行緒,(相當於僕人了,不管了) t.start() t_objs.append(t) for t in t_objs: t.join() #等待所有的子程序結束 print("----------all threads has finished..", threading.current_thread(), threading.active_count())#活動執行緒的個數 print("cost:", time.time()-start_time) #計算整個程序的時間
---恢復內容結束---