對于操作系統(tǒng)來說,一個任務(wù)就是一個進(jìn)程(Process),比如打開一個瀏覽器就是啟動一個瀏覽器進(jìn)程,打開一個記事本就啟動了一個記事本進(jìn)程,打開兩個記事本就啟動了兩個記事本進(jìn)程,打開一個Word就啟動了一個Word進(jìn)程。
有些進(jìn)程還不止同時干一件事,比如Word,它可以同時進(jìn)行打字、拼寫檢查、打印等事情。在一個進(jìn)程內(nèi)部,要同時干多件事,就需要同時運行多個“子任務(wù)”,我們把進(jìn)程內(nèi)的這些“子任務(wù)”稱為線程(Thread)。
進(jìn)程
Python的os模塊封裝了常見的系統(tǒng)調(diào)用,其中包括fork,可以在Python程序中輕松創(chuàng)建子進(jìn)程:
importos
print('Process(%s)start...'%os.getpid())
#OnlyworksonUnix/Linux/Mac:
pid=os.fork()
ifpid==0:
print('Iamchildprocess(%s)andmyparentis%s.'%(os.getpid(),os.getppid()))
else:
print('I(%s)justcreatedachildprocess(%s).'%(os.getpid(),pid))
運行結(jié)果如下:
Process(876)start...
I(876)justcreatedachildprocess(877).
Iamchildprocess(877)andmyparentis876.
由于Windows沒有fork調(diào)用,上面的代碼在Windows上無法運行。由于Mac系統(tǒng)是基于BSD(Unix的一種)內(nèi)核,所以,在Mac下運行是沒有問題的,推薦大家用Mac學(xué)Python!
multiprocessing
如果你打算編寫多進(jìn)程的服務(wù)程序,Unix/Linux無疑是正確的選擇。由于Windows沒有fork調(diào)用,難道在Windows上無法用Python編寫多進(jìn)程的程序?
由于Python是跨平臺的,自然也應(yīng)該提供一個跨平臺的多進(jìn)程支持。multiprocessing模塊就是跨平臺版本的多進(jìn)程模塊。
multiprocessing模塊提供了一個Process類來代表一個進(jìn)程對象,下面的例子演示了啟動一個子進(jìn)程并等待其結(jié)束:
frommultiprocessingimportProcess
importos
#子進(jìn)程要執(zhí)行的代碼
defrun_proc(name):
print('Runchildprocess%s(%s)...'%(name,os.getpid()))
if__name__=='__main__':
print('Parentprocess%s.'%os.getpid())
p=Process(target=run_proc,args=('test',))
print('Childprocesswillstart.')
p.start()
p.join()
print('Childprocessend.')
執(zhí)行結(jié)果如下:
Parentprocess928.
Processwillstart.
Runchildprocesstest(929)...
Processend.
創(chuàng)建子進(jìn)程時,只需要傳入一個執(zhí)行函數(shù)和函數(shù)的參數(shù),創(chuàng)建一個Process實例,用start()方法啟動,這樣創(chuàng)建進(jìn)程比fork()還要簡單。
join()方法可以等待子進(jìn)程結(jié)束后再繼續(xù)往下運行,通常用于進(jìn)程間的同步。
線程
Python的標(biāo)準(zhǔn)庫提供了兩個模塊:_thread和threading,_thread是低級模塊,threading是高級模塊,對_thread進(jìn)行了封裝。絕大多數(shù)情況下,我們只需要使用threading這個高級模塊。
啟動一個線程就是把一個函數(shù)傳入并創(chuàng)建Thread實例,然后調(diào)用start()開始執(zhí)行:
importtime,threading
#新線程執(zhí)行的代碼:
defloop():
print('thread%sisrunning...'%threading.current_thread().name)
n=0
whilen<5:
n=n+1
print('thread%s>>>%s'%(threading.current_thread().name,n))
time.sleep(1)
print('thread%sended.'%threading.current_thread().name)
print('thread%sisrunning...'%threading.current_thread().name)
t=threading.Thread(target=loop,name='LoopThread')
t.start()
t.join()
print('thread%sended.'%threading.current_thread().name)
執(zhí)行結(jié)果如下:
threadMainThreadisrunning...
threadLoopThreadisrunning...
threadLoopThread>>>1
threadLoopThread>>>2
threadLoopThread>>>3
threadLoopThread>>>4
threadLoopThread>>>5
threadLoopThreadended.
threadMainThreadended.
Lock
多線程和多進(jìn)程最大的不同在于,多進(jìn)程中,同一個變量,各自有一份拷貝存在于每個進(jìn)程中,互不影響,而多線程中,所有變量都由所有線程共享,所以,任何一個變量都可以被任何一個線程修改,因此,線程之間共享數(shù)據(jù)最大的危險在于多個線程同時改一個變量,把內(nèi)容給改亂了。
balance=0
lock=threading.Lock()
defrun_thread(n):
foriinrange(100000):
#先要獲取鎖:
lock.acquire()
try:
#放心地改吧:
change_it(n)
finally:
#改完了一定要釋放鎖:
lock.release()
當(dāng)多個線程同時執(zhí)行l(wèi)ock.acquire()時,只有一個線程能成功地獲取鎖,然后繼續(xù)執(zhí)行代碼,其他線程就繼續(xù)等待直到獲得鎖為止。
獲得鎖的線程用完后一定要釋放鎖,否則那些苦苦等待鎖的線程將永遠(yuǎn)等待下去,成為死線程。所以我們用try...finally來確保鎖一定會被釋放。
ThreadLocal
importthreading
#創(chuàng)建全局ThreadLocal對象:
local_school=threading.local()
defprocess_student():
#獲取當(dāng)前線程關(guān)聯(lián)的student:
std=local_school.student
print('Hello,%s(in%s)'%(std,threading.current_thread().name))
defprocess_thread(name):
#綁定ThreadLocal的student:
local_school.student=name
process_student()
t1=threading.Thread(target=process_thread,args=('Alice',),name='Thread-A')
t2=threading.Thread(target=process_thread,args=('Bob',),name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()
執(zhí)行結(jié)果:
Hello,Alice(inThread-A)
Hello,Bob(inThread-B)
全局變量local_school就是一個ThreadLocal對象,每個Thread對它都可以讀寫student屬性,但互不影響。你可以把local_school看成全局變量,但每個屬性如local_school.student都是線程的局部變量,可以任意讀寫而互不干擾,也不用管理鎖的問題,ThreadLocal內(nèi)部會處理。
可以理解為全局變量local_school是一個dict,不但可以用local_school.student,還可以綁定其他變量,如local_school.teacher等等。
ThreadLocal最常用的地方就是為每個線程綁定一個數(shù)據(jù)庫連接,HTTP請求,用戶身份信息等,這樣一個線程的所有調(diào)用到的處理函數(shù)都可以非常方便地訪問這些資源。
以上內(nèi)容為大家介紹了Python學(xué)習(xí)之進(jìn)程和線程,希望對大家有所幫助,如果想要了解更多Python相關(guān)知識,請關(guān)注IT培訓(xùn)機構(gòu):千鋒教育。http://www.dietsnews.net/