Python多線程和隊列操作執行個體

來源:互聯網
上載者:User
Python3,開一個線程,間隔1秒把一個遞增的數字寫入隊列,再開一個線程,從隊列中取出數字並列印到終端

代碼如下:


#! /usr/bin/env python3

import time
import threading
import queue

# 一個線程,間隔一定的時間,把一個遞增的數字寫入隊列
# 生產者
class Producer(threading.Thread):

def __init__(self, work_queue):
super().__init__() # 必須調用
self.work_queue = work_queue

def run(self):
num = 1
while True:
self.work_queue.put(num)
num = num+1
time.sleep(1) # 暫停1秒

# 一個線程,從隊列取出數字,並顯示到終端
class Printer(threading.Thread):

def __init__(self, work_queue):
super().__init__() # 必須調用
self.work_queue = work_queue

def run(self):
while True:
num = self.work_queue.get() # 當隊列為空白時,會阻塞,直到有資料
print(num)

def main():
work_queue = queue.Queue()

producer = Producer(work_queue)
producer.daemon = True # 當主線程退出時子線程也退出
producer.start()

printer = Printer(work_queue)
printer.daemon = True # 當主線程退出時子線程也退出
printer.start()

work_queue.join() # 主線程會停在這裡,直到所有數字被get(),並且task_done(),因為沒有調用task_done(),所在這裡會一直阻塞,直到使用者按^C

if __name__ == '__main__':
main()


queue是安全執行緒的,從多個線程訪問時無需加鎖。
如果在work_queue.get()之後調用work_queue.task_done(),那麼在隊列空時work_queue.join()會返回。
這裡work_queue.put()是間隔一定時間才往隊列放東西,如果調用work_queue.task_done(),在數字1被get()後,隊列空時,join()就返回,程式就結束了。
也就是程式只列印了1然後就退出了。
所以在這種使用情景下,不能調用task_done(),程式會一直迴圈下去。
https://docs.python.org/3/library/queue.html
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.