【发布时间】:2015-09-25 18:18:48
【问题描述】:
我在下面写的代码应该是这样输出的:
<Floor(Thread-3, started 44660)> <Bank(Thread-1, started 43356)> shutting down
<Floor(Thread-4, started 44108)> received a message: shutting down (0, 'UP')
<Bank(Thread-1, started 43356)> received a message: (1, 'DOWN')
<Bank(Thread-1, started 43356)> shutting down
<Bank(Thread-2, started 27800)> shutting down
但是,有时输出的格式似乎不一致。例如:
<Floor(Thread-3, started 27076)> <Bank(Thread-1, started 44608)>shutting down
<Floor(Thread-4, started 28772)>received a message: (shutting down0, 'UP')
<Bank(Thread-1, started 44608)> received a message: (1, 'DOWN')
<Bank(Thread-1, started 44608)> shutting down
<Bank(Thread-2, started 41480)> shutting down
一致的数据在大多数程序中都很重要。为什么这个输出不一致,我该如何防止它?
import threading
import Queue
banks = []
floors = []
class Bank(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.mailbox = Queue.Queue()
banks.append(self.mailbox)
def run(self):
while True:
data = self.mailbox.get()
if data == 'shutdown':
print self, 'shutting down'
return
print self, 'received a message:', data
def stop(self):
banks.remove(self.mailbox)
self.mailbox.put('shutdown')
self.join()
class Floor(threading.Thread):
def __init__(self, number = 0):
threading.Thread.__init__(self)
self.mailbox = Queue.Queue()
floors.append(self.mailbox)
self.number = number
def run(self):
while True:
data = self.mailbox.get()
if data == 'shutdown':
print self, 'shutting down'
return
print self, 'received a message:', data
def stop(self):
floors.remove(self.mailbox)
self.mailbox.put('shutdown')
self.join()
def call(self, data):
banks[0].put((self.number, data))
b0 = Bank()
b1 = Bank()
b0.start()
b1.start()
f0 = Floor(0)
f1 = Floor(1)
f0.start()
f1.start()
f0.call('UP')
f1.call('DOWN')
f0.stop()
f1.stop()
b0.stop()
b1.stop()
【问题讨论】:
-
您所说的“不一致”是指额外的换行符,还是输出比这更交错?
-
@Andy 空格和换行符是可消耗的(但我想知道为什么它们也不一致)。最有趣的部分是
(shutting down0, 'UP')。不知何故,这些消息每隔一段时间就会被连接起来。
标签: multithreading python-2.7 formatting queue