最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python多線程使用方法詳細(xì)講解

 更新時(shí)間:2022年10月12日 09:58:54   作者:Python熱愛者  
這篇文章主要介紹了Python中的多線程實(shí)例,一個(gè)CPU,將時(shí)間切成一片一片的,CPU輪轉(zhuǎn)著去處理一件一件的事情,到了規(guī)定的時(shí)間片就處理下一件事情,更多的相關(guān)內(nèi)容需要的小伙伴可以參考下面文章詳細(xì)

一、簡(jiǎn)介

Python中使用線程有兩種方式:函數(shù)或者用類來包裝線程對(duì)象。

函數(shù)式:調(diào)用 _thread 模塊中的start_new_thread()函數(shù)來產(chǎn)生新線程。

參數(shù)說明:

  • function - 線程函數(shù)。
  • args - 傳遞給線程函數(shù)的參數(shù),他必須是個(gè)tuple類型。
  • kwargs - 可選參數(shù)。

實(shí)例:

import _thread
import time
# 為線程定義一個(gè)函數(shù)
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print ("%s: %s" % ( threadName, time.ctime(time.time()) ))
# 創(chuàng)建兩個(gè)線程
try:
   _thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   _thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print ("Error: 無法啟動(dòng)線程")
while 1:
   pass

二、線程模塊

Python3 通過兩個(gè)標(biāo)準(zhǔn)庫 _thread 和 threading 提供對(duì)線程的支持。

_thread 提供了低級(jí)別的、原始的線程以及一個(gè)簡(jiǎn)單的鎖,它相比于 threading 模塊的功能還是比較有限的。

threading 模塊除了包含 _thread 模塊中的所有方法外,還提供的其他方法:

  • threading.currentThread(): 返回當(dāng)前的線程變量。
  • threading.enumerate(): 返回一個(gè)包含正在運(yùn)行的線程的list。正在運(yùn)行指線程啟動(dòng)后、結(jié)束前,不包括啟動(dòng)前和終止后的線程。
  • threading.activeCount(): 返回正在運(yùn)行的線程數(shù)量,與len(threading.enumerate())有相同的結(jié)果。

除了使用方法外,線程模塊同樣提供了Thread類來處理線程,Thread類提供了以下方法:

  • run(): 用以表示線程活動(dòng)的方法。
  • start():啟動(dòng)線程活動(dòng)。
  • join([time]): 等待至線程中止。這阻塞調(diào)用線程直至線程的join() 方法被調(diào)用中止-正常退出或者拋出未處理的異常-或者是可選的超時(shí)發(fā)生。
  • isAlive(): 返回線程是否活動(dòng)的。
  • getName(): 返回線程名。
  • setName(): 設(shè)置線程名。

三、使用 threading 模塊創(chuàng)建線程

可以通過直接從 threading.Thread 繼承創(chuàng)建一個(gè)新的子類,并實(shí)例化后調(diào)用 start() 方法啟動(dòng)新線程,即它調(diào)用了線程的 run() 方法:

import threading
import time
exitFlag = 0
class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("開始線程:" + self.name)
        print_time(self.name, self.counter, 5)
        print ("退出線程:" + self.name)
def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1
# 創(chuàng)建新線程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 開啟新線程
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("退出主線程")

四、線程同步

如果多個(gè)線程共同對(duì)某個(gè)數(shù)據(jù)修改,則可能出現(xiàn)不可預(yù)料的結(jié)果,為了保證數(shù)據(jù)的正確性,需要對(duì)多個(gè)線程進(jìn)行同步。

使用 Thread 對(duì)象的 Lock 和 Rlock 可以實(shí)現(xiàn)簡(jiǎn)單的線程同步,這兩個(gè)對(duì)象都有 acquire 方法和 release 方法,對(duì)于那些需要每次只允許一個(gè)線程操作的數(shù)據(jù),可以將其操作放到 acquire 和 release 方法之間。

如下:

注意: 多線程的優(yōu)勢(shì)在于可以同時(shí)運(yùn)行多個(gè)任務(wù)(至少感覺起來是這樣)。但是當(dāng)線程需要共享數(shù)據(jù)時(shí),可能存在數(shù)據(jù)不同步的問題。

考慮這樣一種情況:一個(gè)列表里所有元素都是0,線程"set"從后向前把所有元素改成1,而線程"print"負(fù)責(zé)從前往后讀取列表并打印。 那么,可能線程"set"開始改的時(shí)候,線程"print"便來打印列表了,輸出就成了一半0一半1,這就是數(shù)據(jù)的不同步。為了避免這種情況,引入了鎖的概念。 鎖有兩種狀態(tài)——鎖定和未鎖定。每當(dāng)一個(gè)線程比如"set"要訪問共享數(shù)據(jù)時(shí),必須先獲得鎖定;如果已經(jīng)有別的線程比如"print"獲得鎖定了,那么就讓線程"set"暫停,也就是同步阻塞;等到線程"print"訪問完畢,釋放鎖以后,再讓線程"set"繼續(xù)。 經(jīng)過這樣的處理,打印列表時(shí)要么全部輸出0,要么全部輸出1,不會(huì)再出現(xiàn)一半0一半1的尷尬場(chǎng)面。

實(shí)例:

import threading
import time
class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("開啟線程: " + self.name)
        # 獲取鎖,用于線程同步
        threadLock.acquire()
        print_time(self.name, self.counter, 3)
        # 釋放鎖,開啟下一個(gè)線程
        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 = []
# 創(chuàng)建新線程
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()
print ("退出主線程")

五、線程優(yōu)先級(jí)隊(duì)列( Queue)

1、queue隊(duì)列

(1.python3中的隊(duì)列模塊是queue,不是Queue

(2.一般涉及到同步,多線程之類用到隊(duì)列模塊

(3.定義了 queue.Queue 類,以及繼承它的 queue.LifoQueue 類 和 queue.PriorityQueue 類 和 queue.SimpleQueue 類

(4.分別對(duì)應(yīng)隊(duì)列類(FIFO先進(jìn)先出),LIFO后進(jìn)先出隊(duì)列類,優(yōu)先隊(duì)列,無邊界FIFO簡(jiǎn)單隊(duì)列類

(5.還有兩個(gè)異常:隊(duì)滿和隊(duì)空

2、隊(duì)列queue公共方法

'''
學(xué)習(xí)中遇到問題沒人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流群:711312441
尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書!
'''
import queue
#創(chuàng)建基本隊(duì)列
#queue.Queue(maxsize=0)創(chuàng)建一個(gè)隊(duì)列對(duì)象(隊(duì)列容量),若maxsize小于或者等于0,隊(duì)列大小沒有限制
Q=queue.Queue(10)
print(Q)
print(type(Q))
#1.基本方法
print(Q.queue)#查看隊(duì)列中所有元素
print(Q.qsize())#返回隊(duì)列的大小
print(Q.empty())#判斷隊(duì)空
print(Q.full())#判斷隊(duì)滿
#2.獲取隊(duì)列,0--5
#Queue.put(item,block = True,timeout = None )將對(duì)象放入隊(duì)列,阻塞調(diào)用(block=False拋異常),無等待時(shí)間
for i in range(5):
    Q.put(i)
# Queue.put_nowait(item)相當(dāng)于 put(item, False).
#3.讀隊(duì)列,0--5
#Queue.get(block=True, timeout=None)讀出隊(duì)列的一個(gè)元素,阻塞調(diào)用,無等待時(shí)間
while not Q.empty():
    print(Q.get())
# Queue.get_nowait()相當(dāng)于get(False).取數(shù)據(jù),如果沒數(shù)據(jù)拋queue.Empty異常
#4.另兩種涉及等待排隊(duì)任務(wù)的方法
# Queue.task_done()在完成一項(xiàng)工作后,向任務(wù)已經(jīng)完成的隊(duì)列發(fā)送一個(gè)信號(hào)
# Queue.join()阻止直到隊(duì)列中的所有項(xiàng)目都被獲取并處理。即等到隊(duì)列為空再執(zhí)行別的操作

3、其他

(1.LifoQueue: LIFO后進(jìn)先出

(2.PriorityQueue:優(yōu)先級(jí)隊(duì)列,如果數(shù)據(jù)元素不具有可比性,則可將數(shù)據(jù)包裝在忽略數(shù)據(jù)項(xiàng)的類中,僅比較優(yōu)先級(jí)編號(hào)

(3.SimpleQueue:簡(jiǎn)單隊(duì)列,無跟蹤任務(wù)的功能

六、Queue詳細(xì)參數(shù)和用法實(shí)例

Queue 模塊中的常用方法:

  • Queue.qsize() 返回隊(duì)列的大小
  • Queue.empty() 如果隊(duì)列為空,返回True,反之False
  • Queue.full() 如果隊(duì)列滿了,返回True,反之False
  • Queue.full 與 maxsize 大小對(duì)應(yīng)
  • Queue.get([block[, timeout]])獲取隊(duì)列,timeout等待時(shí)間
  • Queue.get_nowait() 相當(dāng)Queue.get(False)
  • Queue.put(item) 寫入隊(duì)列,timeout等待時(shí)間
  • Queue.put_nowait(item) 相當(dāng)Queue.put(item, False)
  • Queue.task_done() 在完成一項(xiàng)工作之后,Queue.task_done()函數(shù)向任務(wù)已經(jīng)完成的隊(duì)列發(fā)送一個(gè)信號(hào)
  • Queue.join() 實(shí)際上意味著等到隊(duì)列為空,再執(zhí)行別的操作

實(shí)例:

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 ("開啟線程:" + self.name)
        process_data(self.name, self.q)
        print ("退出線程:" + 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
# 創(chuàng)建新線程
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1
# 填充隊(duì)列
queueLock.acquire()
for word in nameList:
    workQueue.put(word)
queueLock.release()
# 等待隊(duì)列清空
while not workQueue.empty():
    pass
# 通知線程是時(shí)候退出
exitFlag = 1
# 等待所有線程完成
for t in threads:
    t.join()
print ("退出主線程")

到此這篇關(guān)于Python多線程使用方法詳細(xì)講解的文章就介紹到這了,更多相關(guān)Python多線程內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 如何利用Python隨機(jī)從list中挑選一個(gè)元素

    如何利用Python隨機(jī)從list中挑選一個(gè)元素

    這篇文章主要介紹了如何利用Python隨機(jī)從list中挑選一個(gè)元素,文章通過研究從列表中選擇隨機(jī)元素的不同實(shí)現(xiàn)方法展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-05-05
  • pytorch加載語音類自定義數(shù)據(jù)集的方法教程

    pytorch加載語音類自定義數(shù)據(jù)集的方法教程

    這篇文章主要給大家介紹了關(guān)于pytorch加載語音類自定義數(shù)據(jù)集的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • Python 面向?qū)ο笾恈lass和對(duì)象基本用法示例

    Python 面向?qū)ο笾恈lass和對(duì)象基本用法示例

    這篇文章主要介紹了Python 面向?qū)ο笾恈lass和對(duì)象基本用法,結(jié)合實(shí)例形式詳細(xì)分析了Python面向?qū)ο蟪绦蛟O(shè)計(jì)中類class和對(duì)象基本概念、原理、使用方法與操作注意事項(xiàng),需要的朋友可以參考下
    2020-02-02
  • python os.listdir按文件存取時(shí)間順序列出目錄的實(shí)例

    python os.listdir按文件存取時(shí)間順序列出目錄的實(shí)例

    今天小編就為大家分享一篇python os.listdir按文件存取時(shí)間順序列出目錄的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10
  • Python網(wǎng)絡(luò)編程之socket與socketserver

    Python網(wǎng)絡(luò)編程之socket與socketserver

    這篇文章介紹了Python網(wǎng)絡(luò)編程之socket與socketserver,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-05-05
  • Python之循環(huán)結(jié)構(gòu)

    Python之循環(huán)結(jié)構(gòu)

    今天小編就為大家分享一篇關(guān)于Python之循環(huán)結(jié)構(gòu),小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2019-01-01
  • python中join()方法介紹

    python中join()方法介紹

    Python join() 方法用于將序列中的元素以指定的字符連接生成一個(gè)新的字符串。這篇文章主要介紹了python中join()方法,需要的朋友可以參考下
    2018-10-10
  • Python中字符串類型代碼的執(zhí)行函數(shù)——eval()、exec()和compile()詳解

    Python中字符串類型代碼的執(zhí)行函數(shù)——eval()、exec()和compile()詳解

    這篇文章主要介紹了Python中字符串類型代碼的執(zhí)行函數(shù)——eval()、exec()和compile(),字符串類型代碼的執(zhí)行函數(shù)有三個(gè),都是Python的內(nèi)置函數(shù),下面逐一對(duì)這三個(gè)函數(shù)詳細(xì)講解,需要的朋友可以參考下
    2023-02-02
  • python使用TensorFlow進(jìn)行圖像處理的方法

    python使用TensorFlow進(jìn)行圖像處理的方法

    本篇文章主要介紹了使用TensorFlow進(jìn)行圖像處理的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-02-02
  • pytorch Dataset,DataLoader產(chǎn)生自定義的訓(xùn)練數(shù)據(jù)案例

    pytorch Dataset,DataLoader產(chǎn)生自定義的訓(xùn)練數(shù)據(jù)案例

    這篇文章主要介紹了pytorch Dataset, DataLoader產(chǎn)生自定義的訓(xùn)練數(shù)據(jù)案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03

最新評(píng)論

天门市| 商南县| 临泽县| 岳西县| 马山县| 庆城县| 伊金霍洛旗| 孙吴县| 榆林市| 吉林省| 航空| 绥化市| 武定县| 芦山县| 屯门区| 芜湖市| 昌邑市| 石河子市| 个旧市| 新田县| 枣阳市| 礼泉县| 普宁市| 辛集市| 美姑县| 睢宁县| 郁南县| 桑植县| 平乡县| 凤山县| 萝北县| 丰都县| 皋兰县| 嘉峪关市| 德兴市| 奎屯市| 长宁区| 三明市| 冷水江市| 龙泉市| 柳河县|