Python3.7之多線程學習

參考資料

python多線程官網html

多線程優勢

多線程相似於同時執行多個不一樣程序,多線程運行有以下優勢:
一、使用線程能夠把佔據長時間的程序中的任務放到後臺去處理。
二、用戶界面能夠更加吸引人,好比用戶點擊了一個按鈕去觸發某些事件的處理,能夠彈出一個進度條來顯示處理的進度。
三、程序的運行速度可能加快。
四、一些等待的任務實現上如用戶輸入、文件讀寫和網絡收發數據等,多線程就有用了。能夠釋放一些珍貴的資源如內存佔用等等。python

線程中經常使用的兩個模塊爲:_thread、threading。thread 模塊已被廢棄。用戶可使用 threading 模塊代替。安全

threading 模塊建立線程

經過直接從 threading.Thread 繼承建立一個新的子類,並實例化後調用 start() 方法啓動新線程,即它調用了線程的 run() 方法。網絡

import threading
import time

#繼承threading.Thread類
class feiGegeThread (threading.Thread):
    #線程ID,線程名稱,延遲時間
    def __init__(self, threadID, name, delay):
        threading.Thread.__init__(self);
        self.threadID = threadID;
        self.name = name;
        self.delay = delay;
    #重寫run方法
    def run(self):
        print ("begin thread:" + self.name);
        #調用外部函數
        print_time(self.name, self.delay, 3);
        print ("end thread:" + self.name);

#定義打印時間方法:線程名字、延遲時間、打印次數
def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())));
        counter -= 1;

# 建立新線程
thread1 = feiGegeThread(1, "Thread-1", 1);
thread2 = feiGegeThread(2, "Thread-2", 2);

# 開啓新線程
thread1.start();
thread2.start();
#join方法能夠防止主線程提早結束。
thread1.join();
thread2.join();
#結果
begin thread:Thread-1
begin thread:Thread-2
Thread-1: Sun Jun 16 10:23:48 2019
Thread-2: Sun Jun 16 10:23:49 2019
Thread-1: Sun Jun 16 10:23:49 2019
Thread-1: Sun Jun 16 10:23:50 2019
end thread:Thread-1
Thread-2: Sun Jun 16 10:23:51 2019
Thread-2: Sun Jun 16 10:23:53 2019
end thread:Thread-2

線程同步

若是多個線程共同對某個數據修改,則可能出現不可預料的結果,爲了保證數據的正確性,須要對多個線程進行同步。
使用 Thread 對象的 Lock 和 Rlock 能夠實現簡單的線程同步,這兩個對象都有 acquire 方法和 release 方法,對於那些須要每次只容許一個線程操做的數據,能夠將其操做放到 acquire 和 release 方法之間。多線程

import threading
import time

class myThread (threading.Thread):
    def __init__(self, threadID, name, delay):
        threading.Thread.__init__(self);
        self.threadID = threadID;
        self.name = name;
        self.delay = delay;
    def run(self):
        print ("begin thread: " + self.name);
        # 獲取鎖,用於線程同步
        threadLock.acquire();
        print_time(self.name, self.delay, 3);
        # 釋放鎖,開啓下一個線程
        threadLock.release();

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay);
        print ("%s: %s" % (threadName, time.ctime(time.time())));
        counter -= 1;

#獲取鎖對象
threadLock = threading.Lock();
#盛放線程的列表
threads = [];

# 建立新線程
thread1 = myThread(1, "Thread-1", 1);
thread2 = myThread(2, "Thread-2", 2);

# 開啓新線程
thread1.start();
thread2.start();

# 添加線程到線程列表
threads.append(thread1);
threads.append(thread2);

# 等待全部線程完成,主線程才退出
for t in threads:
    t.join();
結果:
begin thread: Thread-1
begin thread: Thread-2
Thread-1: Sun Jun 16 10:38:27 2019
Thread-1: Sun Jun 16 10:38:28 2019
Thread-1: Sun Jun 16 10:38:29 2019
Thread-2: Sun Jun 16 10:38:31 2019
Thread-2: Sun Jun 16 10:38:33 2019
Thread-2: Sun Jun 16 10:38:35 2019

瞧,打印函數一段時間內只容許一個線程操做。app

線程優先級隊列(Queue)

Python 的 Queue 模塊中提供了同步的、線程安全的隊列類,包括先入先出的隊列 Queue,後入先出的隊列 LifoQueue,和優先級隊列 PriorityQueue。
這些隊列都實現了鎖原語,可以在多線程中直接使用,可使用隊列來實現線程間的同步。函數

import queue
import threading
import time

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self);
        self.threadID = threadID;
        self.name = name;
        self.q = q;
    def run(self):
        print ("begin thread:" + self.name);
        process_data(self.name, self.q);
        print ("end thread:" + self.name);

def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire();
        if not workQueue.empty():
            data = q.get();
            queueLock.release();
            print ("%s processing %s" % (threadName, data));
        else:
            queueLock.release();
        time.sleep(1);

threadList = ["Thread-1", "Thread-2", "Thread-3"];
nameList = ["One", "Two", "Three", "Four", "Five"];
queueLock = threading.Lock();
workQueue = queue.Queue(10);
threads = [];
threadID = 1;

# 建立新線程
for tName in threadList:
    thread = myThread(threadID, tName, workQueue);
    thread.start();
    threads.append(thread);
    threadID += 1;

# 填充隊列
queueLock.acquire();
for word in nameList:
    workQueue.put(word);
queueLock.release();

# 等待隊列清空
while not workQueue.empty():
    pass

# 通知線程是時候退出
exitFlag = 1;

# 等待全部線程完成
for t in threads:
    t.join();
#結果:
begin thread:Thread-1
begin thread:Thread-2
begin thread:Thread-3
Thread-3 processing One
Thread-2 processing Two
Thread-3 processing Three
Thread-1 processing Four
Thread-2 processing Five
end thread:Thread-3
end thread:Thread-1
end thread:Thread-2
相關文章
相關標籤/搜索