1. 程式人生 > >Python的併發程式設計

Python的併發程式設計

程序與執行緒

程序:程式的一次執行,程式裝載記憶體,系統分配資源資料棧等;

執行緒:每個程序都有入口,出口,有優先順序,資源爭搶

GIL全域性直譯器鎖

GLobal Interpreter Lock,GIL並不是Python的特性,是實現CPython時引入的一個概念

GIL是一把全域性排它鎖,同一時間只有一個執行緒在執行,這造成了Python幾乎等於是單執行緒執行的程式

mutiprocessing庫是為了彌補thread庫因為GIL而低效的的缺陷,每一個程序都有自己獨立的GIL,每一個都是一個程序而不是執行緒

from multiprocessing import Process
import time
def f(n):
    time.sleep(1)
    print n*n
if __name__=='__main__':
    for i in range(10):
        p=Process(target=f,args=[i,])
        p.start()

做併發的時候效率比較高

threading模組使用

import time
import threading
def f1():
    pass 
def f2(arg1,arg2):
    time.sleep(1)
    print('正在執行.....')
    print(arg1+arg2)
    f1()
thr=threading.Thread(target=f2,args=(111,222))
thr.start()

thr.setDaemon(True)
thr.join(2)

其中,setDaemon(True)方法裡的引數設定成True則是主執行緒不用等待子執行緒,主執行緒結束之後就將子執行緒結束掉,也稱為守護執行緒,而join(5)是等待執行緒,主執行緒等待子執行緒,子執行緒結束之後主執行緒才能執行,等待的最大的時間就是給定的引數。

threading.currentThread()返回當前的執行緒變數

threading.enumerate()返回正在執行的執行緒的list

threading.activeCount()返回正在執行執行緒的數量,與len(threading.enumerate())的結果一致

threading模組提供的類:  Thread, Lock, Rlock, Condition, [Bounded]Semaphore, Event, Timer, local.

thread(group=None,target=None,name=None,args=(,),kwargs={})

thread.isAlive()

thread.setName()

thread.start()

thread.setDaemon()

thread.join()

多執行緒的event事件

import time
import threading
def do(event):
    print('start')
    event.wait()
    print('ending')
event_org=threading.Event()
for i in range(10):
    thr=threading.Thread(target=do,args=[event_org,])
    thr.start()
event_org.clear()
inp=input('請輸入:')
if inp=='True':
    event_org.set()

threading.Event()的event事件的方法有

event_org.wait() 事件等待。

event_org.set()將事件設定成True,即是事件的開始。

event_org.clear()將事件停止引數設定成,False

event_org.isSet(True),預設是True,要是設定成False將其改成False就好

?????fork操作,呼叫一次返回兩次?????疑問

程序間通訊Queue

Queue是程序安全的佇列