Python 多線程庫總結


多線程庫總結

基於線程的並行性

threading模塊

下面是一些基礎函數,函數包括:

函數
threading.active_count()
threading.current_thread()
threading.get_ident()
threading.enumerate()
threading.main_thread()
threading.settrace(func)
threading.setprofile(func)
threading.stack_size([size])
threading.TIMEOUT_MAX

threading模塊一共提供的類包括:local、Thread、Lock、RLock、Condition、Semaphore、Event、Time

1. Thead-Local Data

專門用來管理線程局部的數據,也就是說一個線程會對應一個local,當前線程無法訪問其它線程的局部數據,線程設置的屬性也不會被其它線程同名的屬性給替換掉。

函數
threading.local

例子如下:

import threading
class MyThread1(threading.Thread):
    def run(self):
        local = threading.local()
        if 'name' not in local.__dict__:
            print('thread1 not set name')
        local.name = 'li'
        print('thread1 {}'.format(local.name))
class MyThread2(threading.Thread):
    def run(self):
        local = threading.local()
        if 'name' not in local.__dict__:
            print('thread2 not set name')
        local.name = 'wang'
        print('thread2 {}'.format(local.name))
def main():
    print("Start main threading")
    local = threading.local()
    local.name = 'main'
    threads = [MyThread1(), MyThread2()]
    for t in threads:
        t.start()
    # 一次讓新創建的線程執行 join
    for t in threads:
        t.join()
    print('main {}'.format(local.name))
if __name__ == '__main__':
    main()

其最后的輸出結果為:

Start main threadingthread1 not set namethread1 lithread2 not set namethread2 wangmain main

2. Thread Obects

函數
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
start()
run()
join(timeout=None)
name
getName()/setName()
ident
is_alive()
daemon
isDaemon()/setDaemon()

線程的創建有兩種實現方式,分別是1.通過將一個可調用對象傳遞到構造函數中;2.通過繼承Thread,在子類中重寫run方法。Thread類定義為:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
# group應為None;保留用於在實現ThreadGroup類時的未來擴展。
# target是將被run()方法調用的可調用對象。默認為None,表示不調用任何東西。
# name是線程的名字。默認情況下,以“Thread-N”的形式構造一個唯一的名字,N是一個小的十進制整數。
# args是給調用目標的參數元組。默認為()。
# kwargs是給調用目標的關鍵字參數的一個字典。默認為{}。
# 如果daemon不是None,守護程序顯式設置線程是否為daemonic。如果為None(默認值),daemonic屬性從當前線程繼承。

注意:應該始終以關鍵字參數調用該構造函數。

3. Lock Objects

為了保證數據的准確性,引入了鎖的概念,原鎖是一個同步原語,是當前可用的最低級同步原語。

函數
class threading.Lock
acquire(blocking=True, timeout=-1)
release()

4. RLock Objects

和Lock的區別在於RLock允許在同一線程中被多次acquire,但是Lock卻不允許這種情況,使用acquire的次數需要和release的次數相互對應;

函數
class threading.Lock
acquire(blocking=True, timeout=-1)
release()

5. Condition Objects

條件變量總是與某種鎖相關聯

函數
class threading.Condition(lock=None)
acquire(*args)
release()
wait(timeout=None)
wait_for(predicate, timeout=None)
notify(n=1)
notify_all()

6. Semaphore Objects

信號量管理內部計數器,每個acquire()調用遞減,每個release()調用遞增。計數器永遠不會低於零;當acquire()發現它為零時,它阻塞,等待其他線程調用release()。

函數
class threading.Semaphore(value=1)
class threading.BoundedSemaphore(value=1)
acquire(blocking=True, timeout=None)
release()

7. Event Objects

事件對象是線程間最簡單的通信機制之一:線程可以激活在一個事件對象上等待的其他線程。每個事件對象管理一個內部標志,可以在事件對象上調用set() 方法將內部標志設為true,調用 clear() 方法將內部標志重置為false。wait()方法將阻塞直至該標志為真。

函數
class threading.Event
is_set()
set()
clear()
wait(timeout=None)

8. Timer Objects

這個類表示一個動作應該在一個特定的時間之后運行 — 也就是一個計時器。Timer是Thread的子類, 因此也可以使用函數創建自定義線程

函數
class threading.Timer(interval, function, args=None, kwargs=None)
cancel()

9. Barrier Objects

這個類提供了一個簡單的同步原語,供需要彼此等待的固定數量的線程使用。每個線程嘗試通過調用wait()方法傳遞屏障,並將阻塞,直到所有線程都調用。

函數和屬性
class threading.Barrier(parties, action=None, timeout=None)
wait(timeout=None)
reset()
abort()
parties
n_waiting
broken
exception threading.BrokenBarrierError

參考線程總結

項目:

  1. 實現一
  2. 實現二


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM