python - Getting different result in different runs with multithreading -


why when code executed, result different every time?

i tried follow how code executed, , confused, feel not sense.

and result appear randomly every time

#!/usr/bin/python  import queue import threading import time  exitflag = 0  class mythread (threading.thread):     def __init__(self, threadid, name, q):         threading.thread.__init__(self)         self.threadid = threadid         self.name = name         self.q = q     def run(self):         print "starting " + self.name         process_data(self.name, self.q)         print "exiting " + self.name  def process_data(threadname, q):     while not exitflag:         queuelock.acquire()         if not workqueue.empty():             data = q.get()             queuelock.release()             print "%s processing %s" % (threadname, data)         else:             queuelock.release()         time.sleep(1)  threadlist = ["thread-1", "thread-2", "thread-3"] namelist = ["one", "two", "three", "four", "five"] queuelock = threading.lock() workqueue = queue.queue(10) threads = [] threadid = 1  # create new threads tname in threadlist:     thread = mythread(threadid, tname, workqueue)     thread.start()     threads.append(thread)     threadid += 1  # fill queue queuelock.acquire() word in namelist:     workqueue.put(word) queuelock.release()  # wait queue empty while not workqueue.empty():     pass  # notify threads it's time exit exitflag = 1  # wait threads complete t in threads:     t.join() print "exiting main thread" 

code source http://www.tutorialspoint.com/python/python_multithreading.htm


update

sorry, mean order of result

like this:

starting thread-1 starting thread-2 starting thread-3 thread-3 processing 1 thread-2 processing 2 thread-1 processing 3 thread-3 processing 4 thread-2 processing 5 exiting thread-1 exiting thread-3 exiting thread-2 exiting main thread [finished in 3.0s] 

and when try again, result

starting thread-1 starting thread-2 starting thread-3 thread-3 processing 1 thread-2 processing 2 thread-1 processing 3 thread-3 processing 4 thread-3 processing 5 exiting thread-1 exiting thread-2 exiting thread-3 exiting main thread [finished in 3.0s] 

i assume, "result" mean execution order. 1 idea behind mutithreading is, don't have care execution order unless want specify explicitely. totally dependent on underlying operating system, system load, ... etc.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -