欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python多線程入門學(xué)習(xí)

 更新時間:2021年12月13日 08:38:27   作者:Python程序u猿  
這篇文章主要介紹了Python多線程入門學(xué)習(xí),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

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

函數(shù)式:

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

語法如下:

thread.start_new_thread(function, args[, kwargs])

參數(shù)說明:

  • function - 線程函數(shù)。
  • args - 傳遞給線程函數(shù)的參數(shù),它必須是個 tuple 類型。
  • kwargs - 可選參數(shù)。
import thread
import time
 
# 為線程定義一個函數(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)建兩個線程
try:
   thread.start_new_thread(print_time, ("Thread-1", 2,))
   thread.start_new_thread(print_time, ("Thread-2", 4,))
except:
   print ("Error: unable to start thread")
 
while 1:
   pass

使用 Threading 模塊創(chuàng)建線程

使用 Threading模塊創(chuàng)建線程,直接從 threading.Thread 繼承,然后重寫__init__方法和 run 方法:

import threading
import time
 
exitFlag = 0
 
class myThread (threading.Thread):   #繼承父類threading.Thread
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):                   #把要執(zhí)行的代碼寫到run函數(shù)里面 線程在創(chuàng)建后會直接運(yùn)行run函數(shù) 
        print ("Starting " + self.name)
        print_time(self.name, self.counter, 5)
        print ("Exiting " + self.name)
 
def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            (threading.Thread).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()
 
print ("Exiting Main Thread")

線程同步

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

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

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 ("Starting " + self.name)
       # 獲得鎖,成功獲得鎖定后返回True
       # 可選的timeout參數(shù)不填時將一直阻塞直到獲得鎖定
       # 否則超時后將返回False
        threadLock.acquire()
        print_time(self.name, self.counter, 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 = []
 
# 創(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 ("Exiting Main Thread")

線程優(yōu)先級隊列(Queue)

Python 的 Queue 模塊中提供了同步的、線程安全的隊列類,包括 FIFO(先入先出)隊列 Queue,LIFO(后入先出)隊列 LifoQueue 和優(yōu)先級隊列 PriorityQueue。這些隊列都實(shí)現(xiàn)了鎖原語,能夠在多線程中直接使用。可以使用隊列來實(shí)現(xiàn)線程間的同步。

Queue 模塊中的常用方法:

  • Queue.qsize() 返回隊列的大小
  • Queue.empty() 如果隊列為空,返回True,反之False
  • Queue.full() 如果隊列滿了,返回True,反之False
  • Queue.full 與 maxsize 大小對應(yīng)
  • Queue.get([block[, timeout]])獲取隊列,timeout等待時間
  • Queue.get_nowait() 相當(dāng)Queue.get(False)
  • Queue.put(item) 寫入隊列,timeout等待時間
  • Queue.put_nowait(item) 相當(dāng)Queue.put(item, False)
  • Queue.task_done() 在完成一項工作之后,Queue.task_done()函數(shù)向任務(wù)已經(jīng)完成的隊列發(fā)送一個信號
  • Queue.join() 實(shí)際上意味著等到隊列為空,再執(zhí)行別的操作
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 ("Starting " + self.name)
        process_data(self.name, self.q)
        print ("Exiting " + 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
 
# 填充隊列
queueLock.acquire()
for word in nameList:
    workQueue.put(word)
queueLock.release()
 
# 等待隊列清空
while not workQueue.empty():
    pass
 
# 通知線程是時候退出
exitFlag = 1
 
# 等待所有線程完成
for t in threads:
    t.join()
print ("Exiting Main Thread")

到此這篇關(guān)于Python多線程入門學(xué)習(xí)的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 詳解使用PyInstaller將Pygame庫編寫的小游戲程序打包為exe文件

    詳解使用PyInstaller將Pygame庫編寫的小游戲程序打包為exe文件

    這篇文章主要介紹了詳解使用PyInstaller將Pygame庫編寫的小游戲程序打包為exe文件,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • pytorch?plt.savefig()的用法及保存路徑

    pytorch?plt.savefig()的用法及保存路徑

    這篇文章主要給大家介紹了關(guān)于pytorch?plt.savefig()的用法及保存路徑的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2022-01-01
  • pytorch鎖死在dataloader(訓(xùn)練時卡死)

    pytorch鎖死在dataloader(訓(xùn)練時卡死)

    這篇文章主要介紹了pytorch鎖死在dataloader(訓(xùn)練時卡死),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • tensorflow實(shí)現(xiàn)簡單的卷積神經(jīng)網(wǎng)絡(luò)

    tensorflow實(shí)現(xiàn)簡單的卷積神經(jīng)網(wǎng)絡(luò)

    這篇文章主要為大家詳細(xì)介紹了tensorflow實(shí)現(xiàn)簡單的卷積神經(jīng)網(wǎng)絡(luò),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-05-05
  • 解決Python?Pandas?DataFrame表格打印輸出不能對齊的問題

    解決Python?Pandas?DataFrame表格打印輸出不能對齊的問題

    這篇文章主要介紹了解決Python?Pandas?DataFrame表格打印輸出不能對齊的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • 零基礎(chǔ)寫python爬蟲之抓取糗事百科代碼分享

    零基礎(chǔ)寫python爬蟲之抓取糗事百科代碼分享

    前面我們介紹了如何抓取百度貼吧文章,然后講解了python的神器正則表達(dá)式,下面,我們就把2者結(jié)合起來,詳細(xì)介紹下,如何來抓取到糗事百科里面的指定內(nèi)容
    2014-11-11
  • pandas中Series的使用方式

    pandas中Series的使用方式

    這篇文章主要介紹了pandas中Series的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • 詳解pyinstaller selenium python3 chrome打包問題

    詳解pyinstaller selenium python3 chrome打包問題

    這篇文章主要介紹了詳解pyinstaller selenium python3 chrome打包問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-10-10
  • python顏色隨機(jī)生成器的實(shí)例代碼

    python顏色隨機(jī)生成器的實(shí)例代碼

    這篇文章主要介紹了python顏色隨機(jī)生成器的實(shí)例代碼,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-01-01
  • Python 列表反轉(zhuǎn)顯示的四種方法

    Python 列表反轉(zhuǎn)顯示的四種方法

    這篇文章主要介紹了Python 列表反轉(zhuǎn)顯示的四種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11

最新評論