2016-04-01 82 views
0

我想测试这个简单的代码,我发现在Pydev使用线程模块,因为线程模块不是我的选项。线程甚至不运行,它所做的只是打印HELLO并退出程序。我用我的原始程序使用这个模块,但它做的是同样的事情,所以我想我会从源码的简单测试开始。这是为什么发生?Python线程模块

代码:

import thread 
import time 

# Define a function for the thread 
def print_time(threadName, delay): 
    count = 0 
    while count < 5: 
     time.sleep(delay) 
     count += 1 
     print "%s: %s" % (threadName, time.ctime(time.time())) 

# Create two threads as follows 
try: 
    thread.start_new_thread(print_time, ("Thread-1", 2,)) 
    thread.start_new_thread(print_time, ("Thread-2", 4,)) 
except: 
    print "Error: unable to start thread" 

print "HELLO" 

它甚至不产生任何错误或异常。

回答

0

的问题是,你的主线程在结束之前,你可以看到任何线程的输出,只是把延迟在主线程中底:

print "HELLO" 
time.sleep(20) 

如果您正在使用的threading模块,您也可以使用线程.join()方法等待它完成,但我不确定thread模块中的等效项。

+0

真棒谢谢你! – shapiro