【发布时间】:2013-01-06 10:20:11
【问题描述】:
我使用 Python 已经有一段时间了,但在今天之前我从未真正用它做过任何并发操作。我偶然发现了this blog post,并决定做一个类似(但更简单)的例子:
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()
它似乎工作正常,但打印件似乎有一些我无法弄清楚的问题。几个测试运行:
chris@DPC3:~/code/pythonthreading$ python owntest.py
0 :: BLUBTOR
1 :: more nonsense
3 :: cookies taste good
2 :: what is?!
chris@DPC3:~/code/pythonthreading$ python owntest.py
0 :: BLUBTOR
2 :: more nonsense
3 :: cookies taste good0 :: what is?!
chris@DPC3:~/code/pythonthreading$ python owntest.py
2 :: BLUBTOR
3 :: more nonsense1 :: cookies taste good
2 :: what is?!
chris@DPC3:~/code/pythonthreading$
为什么输出格式这么奇怪?
【问题讨论】:
-
你可以改用
sys.stdout.write(message):)
标签: python multithreading output