線程:
線程是操作系統(tǒng)能夠進行運算調度的最小單位。線程被包含在進程中,是進程中實際處理單位。一條線程就是一堆指令集合。
一條線程是指進程中一個單一順序的控制流,一個進程中可以并發(fā)多個線程,每條線程并行執(zhí)行不同的任務。
進程:
進程(Process)是計算機中的程序關于某數(shù)據(jù)集合上的一次運行活動,是系統(tǒng)進行資源分配和調度的基本單位,是操作系統(tǒng)結構的基礎。
區(qū)別:
進程(process)是一塊包含了某些資源的內存區(qū)域。操作系統(tǒng)利用進程把它的工作劃分為一些功能單元。
進程中所包含的一個或多個執(zhí)行單元稱為線程(thread)。進程還擁有一個私有的虛擬地址空間,該空間僅能被它所包含的線程訪問。
線程只能歸屬于一個進程并且它只能訪問該進程所擁有的資源。當操作系統(tǒng)創(chuàng)建一個進程后,該進程會自動申請一個名為主線程或首要線程的線程。
處理IO密集型任務或函數(shù)用線程;
處理計算密集型任務或函數(shù)用進程。
創(chuàng)建線程
導入模塊threading,通過threading.Thread()創(chuàng)建線程。其中target接收的是要執(zhí)行的函數(shù)名字,args接收傳入函數(shù)的參數(shù),以元組()的形式表示。
啟動線程
通過線程對象j.start()啟動線程。
j.join()
在子線程執(zhí)行完成之前,這個子線程的父線程將一直被阻塞。就是說,當調用join()的子進程沒有結束之前,主進程不會往下執(zhí)行。對其它子進程沒有影響。
from time import ctime,sleep
import threading
def talk(content,loop):
for i in range(loop):
print("start Talk %s %s" %(content,ctime()) )
sleep(3)
def write(content,loop):
for i in range(loop):
print("start Write %s %s" %(content,ctime()))
sleep(3)
threads=[]
t1=threading.Thread(target=talk,args=('hello,my friends',2))
threads.append(t1)
t2=threading.Thread(target=write,args=('nice to see you',2))
threads.append(t2)
if __name__=='__main__':
for j in threads:
j.start()
for j in threads:
j.join()
print("all the end %r" %ctime())