想在python中实现线程间通信

时间:2013-07-19 08:48:44

标签: python python-multithreading

我正在开发python中的自动化套件,我想到的是,经过一段时间后,我的自动化套件应该被停止,或者换句话说,自动化套件需要在规定的时间内完成其执行。所以我的想法是启动主程序,它将创建两个线程1.自动化套件和2.定时器线程。所以只要时间流逝,我的第二个线程就会停止第一个自动化线程。 以下是可能满足上述要求的示例代码,

import threading
import time

class myThread (threading.Thread):
    def __init__(self, threadID, name):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name

    def run(self):
        print "Starting " + self.name
        if self.threadID==1:
            self.timeout(60)            
        else:
            self.Automation_Suite("XYZ")
        print "Exiting " + self.name

    def timeout(self,delay):        
        while delay!=0:
            time.sleep(1)
            delay=delay-1

    def Automation_Suite(self,name):
        count=500000
        while count!=0:
            print name
            count=count-1

# Create new threads
thread1 = myThread(1, "Thread-1")
thread2 = myThread(2, "Thread-2")

# Start new Threads
thread1.start()
thread2.start()
if not thread1.is_alive():
    thread2.join()

print "Exiting Main Thread"

但是上面的代码不起作用,循环无限。那么请建议更好的解决方案来满足要求吗?

谢谢, Priyank Shah

1 个答案:

答案 0 :(得分:0)

如果我改变了Automation_Suite

def Automation_Suite(self,name):
    count=5
    while count!=0:
        print name, count
        count=count-1

我得到了这个输出

Starting Thread-1Starting Thread-2
XYZ 5
XYZ 4

XYZExiting Main Thread
 3
XYZ 2
XYZ 1
Exiting Thread-2

这看起来很糟糕,但我觉得你只是不耐烦了。如果我在超时功能中打印延迟,我会看到它慢慢倒数到0。 加入你开始的每一个帖子都比较整洁:

thread1.start()
thread2.start()
thread1.join()
thread2.join()