我已經和Python一起工作了一段時間,但在今天之前我從未真正做過任何併發。我偶然發現this blog post,並決定做一個類似(但簡單)例如:爲什麼我的Python程序的輸出看起來很奇怪?
import os
import threading
import Queue
class Worker(threading.Thread):
def __init__(self, queue, num):
threading.Thread.__init__(self)
self.queue = queue
self.num = num
def run(self):
while True:
text = self.queue.get()
#print "{} :: {}".format(self.num, text)
print "%s :: %s" % (self.num, text)
self.queue.task_done()
nonsense = ["BLUBTOR", "more nonsense", "cookies taste good", "what is?!"]
queue = Queue.Queue()
for i in xrange(4):
# Give the worker the queue and also its "number"
t = Worker(queue, i)
t.setDaemon(True)
t.start()
for gibberish in nonsense:
queue.put(gibberish)
queue.join()
這似乎很好地工作,但似乎有一些問題,我想不通的打印。幾個測試運行:
[email protected]:~/code/pythonthreading$ python owntest.py
0 :: BLUBTOR
1 :: more nonsense
3 :: cookies taste good
2 :: what is?!
[email protected]:~/code/pythonthreading$ python owntest.py
0 :: BLUBTOR
2 :: more nonsense
3 :: cookies taste good0 :: what is?!
[email protected]:~/code/pythonthreading$ python owntest.py
2 :: BLUBTOR
3 :: more nonsense1 :: cookies taste good
2 :: what is?!
[email protected]:~/code/pythonthreading$
爲什麼輸出的格式奇怪呢?
您可以使用'sys.stdout.write(message)'代替:) –