the code wrote below supposed output along lines of this:
<floor(thread-3, started 44660)> <bank(thread-1, started 43356)> shutting down <floor(thread-4, started 44108)> received message: shutting down (0, 'up') <bank(thread-1, started 43356)> received message: (1, 'down') <bank(thread-1, started 43356)> shutting down <bank(thread-2, started 27800)> shutting down
however, formatting of output seems inconsistent @ times. example:
<floor(thread-3, started 27076)> <bank(thread-1, started 44608)>shutting down <floor(thread-4, started 28772)>received message: (shutting down0, 'up') <bank(thread-1, started 44608)> received message: (1, 'down') <bank(thread-1, started 44608)> shutting down <bank(thread-2, started 41480)> shutting down
consistent data important in programs. why output inconsistent , how prevent it?
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 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 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()
ultimately, since call()
calls being executed in distinct threads, there nothing guarantees execute (and output) synchronously. if want guarantee output not interleaved, you'll need place large global lock (mutex) around print calls.
even won't guarantee ordered consistently - example different lines above can switched - in case you'll need lock chain calls. incidentally, negate performance advantage of multithreading in first place.
Comments
Post a Comment