簡體   English   中英

帶有同步隊列的python線程

[英]python threading with sync queue

在這個示例中,我有一個遵循相同邏輯的腳本。 基本上,我將項目插入到全局隊列中,並生成帶有while循環的線程,該循環從隊列中獲取和項,並調用task_done。

如果我的while循環正在檢查隊列是否為空,那么我可以讓線程加入,但是我想嘗試合並一個可以設置自己退出循環的標志。 當我嘗試執行此操作時,請永久加入線程塊。

這是不加入線程的無效示例:

import threading
import queue

class Mythread(threading.Thread):
    def __init__(self):
        super().__init__()
        self.signal = False
    def run(self):
       global queue
       while not self.signal:
           item = q.get()
           print(item)
           q.task_done()
    def stop(self):
       self.signal = True

q = queue.Queue
for i in range(5000):
   q.put(i)

threads = []
for i in range(2):
    t = Mythread()
    threads.append(t)

for t in threads:
    t.start()
q.join()

for t in threads:
    print(t.signal)   <---- False
    t.stop()             
    print(t.signal)   <---- True
    t.join()          <---- Blocks forever

這是使用空隊列的作品

import threading
import queue

class Mythread(threading.Thread):
    def __init__(self):
        super().__init__()
    def run(self):
        global queue
        while not q.empty():
            item = q.get()
            print(item)
            q.task_done()

q = queue.Queue
for i in range(5000):
   q.put(i)

threads = []
for i in range(2):
    t = Mythread()
    threads.append(t)

for t in threads:
    t.start()

q.join()

for t in threads:
    t.join()          <---- Works fine
    print(t.is_alive())   <--- returns False

有任何想法嗎?

q.get塊,使其不會達到您的條件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM