在多线程程序中控制解释器

时间:2011-12-31 16:32:13

标签: python

在python解释器模式中,我启动了一个指向函数的线程,该函数在无限循环中打印语句。现在我想再次控制解释器以启动另一个线程。我怎样才能回到interperter>>?

1 个答案:

答案 0 :(得分:2)

让我们说这是你的代码(from http://mundogeek.net/ ¿QUÉ SON LOS PROCESOS Y LOS THREADS?):

import threading  

class MiThread(threading.Thread):  
      def __init__(self, num):  
          threading.Thread.__init__(self)  
          self.num = num  

      def run(self):  
          while true:
             print "Soy el hilo", self.num  

print "Soy el hilo principal"  

for i in range(0, 10):  
    t = MiThread(i)  
    t.start()  

然后,insteat将打印发送到控制台,您可以将输出重定向到文件:

      def run(self):  
          f = open('/tmp/workfile{0}.txt'.format(self.num), 'r+')
          while true:
             f.write("Soy el hilo {0}\n".format( self.num ))

或者您可以创建一个返回您自己的线程状态信息的线程方法/属性:

class MiThread(threading.Thread):  
      def __init__(self, num):  
          threading.Thread.__init__(self)  
          self.num = num  
          self.status = ''

      def run(self):  
          while true:
             self.status = "Soy el hilo {0}".format( self.num )


t1 = MiThread(i)  
t1.start()  
t2 = MiThread(i)  #<-- at this point you get back interpreter
t2.start()  
print t1.status
相关问题