python 線程 Thread

啓動線程- threading

  • 將函數傳入並創建Thread實例,然後調用start()
threading.Thread(group=None,target=None,name=None,args=(),kwsrgs{})
  • groupNone被保留用來未來實現ThreadGroup類的擴展
  • target爲被run()``方法調用的對象。默認爲None`,表示不調用任何東西。
  • name是線程的名字,可以自己設定,python默認爲:Thread-N,N爲十進制數。
  • args:表示被調用的函數的參數,爲一個元祖
  • kwargs:給調用目標的關鍵字參數的字典,默認爲{}

- 任何進程默認會啓動一個線程,該線程未主線程,名字是:MainThread,主線程可以啓動新線程,子線程的名字在創建的時候創建。

import time,threading
def loop():
    """
    #新線程的執行代碼
    :return: 無返回
    """
    print('線程%s運行中----'% threading.current_thread().name)#返回當前線程的實例
    n=0
    while n<5:
        n=n+1
        print('線程 %s>>>%s' %(threading.current_thread().name,n))
        time.sleep(1)
    print('線程%s結束了' %threading.current_thread().name)
print('線程%s運行中----'% threading.current_thread().name)
t=threading.Thread(target=loop,name='child')
t.start()
t.join()
print('線程%s結束了' %threading.current_thread().name)

輸出:

線程MainThread運行中----
線程child運行中----
線程 child>>>1
線程 child>>>2
線程 child>>>3
線程 child>>>4
線程 child>>>5
線程child結束了
線程MainThread結束了

線程鎖 LOCK

當多個線程一起執行時,就有可能會出現變量的值不太常理出牌。
這個時候就需要一個鎖把線程鎖住,先把當前的執行完了,再執行別的。但是這樣就不能該保證併發,同時也可以使用鎖把不同的線程鎖在一起,但是也會出現每個線程都被鎖着,一直轉轉轉。
舉個例子吧:

import time, threading

# 假定這是你的銀行存款:
balance = 0
lock = threading.Lock()
def change_it(n):
    # 先存後取,結果應該爲0:
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
   for i in range(100000):
        # 先要獲取鎖:
        lock.acquire()
        try:
            # 放心地改吧:
            change_it(n)
        finally:
            # 改完了一定要釋放鎖:
            lock.release()

t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章