python中queue使用_在python2.6中使用Queue类
假設我一直在使用Python2.6,無法升級(即使這會有幫助)。我編寫了一個使用Queue類的程序。我的producer是一個簡單的目錄列表。我的使用者線程從隊列中提取一個文件,并對其進行處理。如果文件已經處理過,我跳過它。已處理的列表是在所有線程啟動之前生成的,因此它不是空的。在
這里有一些偽代碼。在import Queue, sys, threading
processed = []
def consumer():
while True:
file = dirlist.get(block=True)
if file in processed:
print "Ignoring %s" % file
else:
# do stuff here
dirlist.task_done()
dirlist = Queue.Queue()
for f in os.listdir("/some/dir"):
dirlist.put(f)
max_threads = 8
for i in range(max_threads):
thr = Thread(target=consumer)
thr.start()
dirlist.join()
我得到的奇怪行為是,如果一個線程遇到一個已經被處理的文件,線程就會暫停并等待直到整個程序結束。我做了一點測試,前7個線程(假設8個是最大值)停止,而第8個線程繼續處理,一次一個文件。但是,這樣做,我就失去了應用程序線程化的全部理由。在
是我做錯了什么,還是這是Python2.6中隊列/線程類的預期行為?在
總結
以上是生活随笔為你收集整理的python中queue使用_在python2.6中使用Queue类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Win11 Build 22000.22
- 下一篇: python ljust 库_Pytho