python學習之5 多線程threading

python學習之5 多線程threading

模塊

python自帶兩個模塊,爲thread和threading。
常用的爲threading模塊。

threading模塊

Thread 線程類,這是我們用的最多的一個類,你可以指定線程函數執行或者繼承自它都可以實現子線程功能;
Timer與Thread類似,但要等待一段時間後纔開始運行;
Lock 鎖原語,這個我們可以對全局變量互斥時使用;
RLock 可重入鎖,使單線程可以再次獲得已經獲得的鎖;
Condition 條件變量,能讓一個線程停下來,等待其他線程滿足某個“條件”;
Event 通用的條件變量。多個線程可以等待某個事件發生,在事件發生後,所有的線程都被激活;
Semaphore爲等待鎖的線程提供一個類似“等候室”的結構;
BoundedSemaphore 與semaphore類似,但不允許超過初始值;
Queue:實現了多生產者(Producer)、多消費者(Consumer)的隊列,支持鎖原語,能夠在多個線程之間提供很好的同步支持。

其中Thread類

是你主要的線程類,可以創建進程實例。該類提供的函數包括:
getName(self) 返回線程的名字
isAlive(self) 布爾標誌,表示這個線程是否還在運行中
isDaemon(self) 返回線程的daemon標誌
join(self, timeout=None) 程序掛起,直到線程結束,如果給出timeout,則最多阻塞timeout秒
run(self) 定義線程的功能函數
setDaemon(self, daemonic) 把線程的daemon標誌設爲daemonic
setName(self, name) 設置線程的名字
start(self) 開始線程執行

練習源碼

# coding = utf-8
#########################
# #coding by 劉雲飛
#########################

import threading as th
from time import ctime, sleep

counter = 0
mutex = th.Lock()


class MyThread(th.Thread):
    def __init__(self):
        th.Thread.__init__(self)

    def run(self):
        global counter, mutex
        sleep(1)
        if mutex.acquire():
            counter += 1
            print('this is ', self.name, ',counter is ', counter)
            mutex.release()


if __name__ == '__main__':
    for i in range(100):
        ths = MyThread()
        ths.start()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章