1. 程式人生 > >39. Python 多線程實例 多線程鎖

39. Python 多線程實例 多線程鎖

python 多線程 鎖

1.多線程

多線程和多進程的表現形式差不多

IO密集型用多線程

線程是應用程序中的最小單元

多線程的實現有兩種方式:

方法一:

將要執行的方法作為參數傳給Thread的構造方法(和多進程類似)

t = threading.Thread(target=action, args=(i,))


方法二:

從Thread繼承,並重寫run()

看源碼:

P = threading.Thread
p.start() -> _start_new_thread(self.__bootstrap, ()) -> self.__bootstrap_inner() -> self.run()
try:
    if self.__target:
        self.__target(*self.__args, **self.__kwargs)

所以如果重寫了run,就直接調用run的函數了,如果run沒有重新,就調用target函數。


舉例:

import threading
def worker(n):
    print ("start worker{0}".format(n))

class MyThread(threading.Thread):
    def __init__(self, args):
        super(MyThread, self).__init__()
        self.args = args
    def run(self):
        print ("start MyThread{0}".format(self.args))
        
if __name__ == "__main__":
    for i in xrange(1, 6):
        t1 = threading.Thread(target=worker, args=(i,))
        t1.start()
    t1.join()
    for x in xrange(6, 11):
        t2 = MyThread(x)
        t2.start()
    t2.join()

返回結果:

start worker1
start worker2
start worker3
start worker4
start worker5
start MyThread6
start MyThread7
start MyThread8
start MyThread9
start MyThread10


多線程鎖:

寫法與多進程很多都類似

通過threading.Lock()來創建鎖,函數在執行的只有先要獲得鎖,然後執行完以後要釋放鎖:

with lock:
lock.acquire()
lock.release()


舉例:

import threading
import time


def  worker(name, lock):
    with lock:
        print ("start {0}".format(name))
        time.sleep(1)
        print ("end  {0}".format(name))

if __name__ == "__main__":
    lock = threading.Lock()
    t1 = threading.Thread(target=worker, args=("worker1",lock))
    t2 = threading.Thread(target=worker, args=("worker2",lock))
    t1.start()
    t2.start()
    print ("main end")


返回結果:

start worker1
main end
end  worker1
start worker2
end  worker2


由結果可知:

按依次的順序來執行,誰先獲得這個鎖以後誰先來執行,當他執行完畢後,將鎖釋放掉,下一個函數來執行的時候,才能夠獲得鎖來執行。


39. Python 多線程實例 多線程鎖