0

Two threads in this program,when this program run for a while,there only one thread print it's myid,why? what's wrong with the other thead?

from threading import Thread  
from time import sleep  

class MyThread(Thread):  
      def __init__(self,myid):  
          Thread.__init__(self)  
          self.myid = myid  
          print self.myid  
      def run(self):  
          flag = True  
          while flag:  
              try:  
                  print self.myid  
                  sleep(0.1)  
              except Exception,e:  
                  print e  
                  flag = False  


if __name__ =="__main__":  
      threads = []  
      for i in range(1,3):  
          t = MyThread(i)  
          threads.append(t)  
      for t in threads:  
          t.start()  
      threads[0].join()  
      print '1 is finished'  
      threads[1].join()  
      print '2 is finished'  
      print 'All finished'  
Fernando Freitas Alves
  • 3,709
  • 3
  • 26
  • 45
wei zhang
  • 11
  • 3
  • 1
    Threading is not a good approach in python to scale. Refer: http://wiki.python.org/moin/GlobalInterpreterLock You should run multiple python processes instead to scale. – Sagar Hatekar Mar 06 '13 at 04:05
  • I get 1's and 2's interspersed (as expected). What operating system are you using? – Warren Weckesser Mar 06 '13 at 04:20
  • To follow up on @SagarHatekar's comment you might want to check out [one of my previous answers](http://stackoverflow.com/a/14598595/849425) for an example of multiprocessing using the `multiprocessing.Pool` object. –  Mar 06 '13 at 04:37
  • I run this program on windows using IDLE – wei zhang Mar 06 '13 at 06:52
  • http://stackoverflow.com/questions/1595649/threading-in-a-pyqt-application-use-qt-threads-or-python-threads – Alexander Mar 07 '13 at 05:36
  • is this the problem of using 'print' in many threads?@SagarHatekar – wei zhang Mar 07 '13 at 07:21

0 Answers0