【发布时间】:2014-08-03 05:41:20
【问题描述】:
我一直在尝试编写一段测试代码,该代码将不断打印“正在运行”,直到按下某个键。我试图通过创建一个额外的线程(称为 thread1)来监听按键来实现这一点。
当我运行我的代码时,线程启动正常,并且在调用 getch.getch() 之前似乎可以正常执行。当 getch.getch() 正在等待按键时,它似乎不仅停止了 thread1,而且还停止了主线程。
如何确保在 thread1 监听按键时,主线程继续运行?
我正在使用 python 2.7 和 getch 1.0 (https://pypi.python.org/pypi/getch)。
这是我的代码:
import threading
import time
import getch
class myThread (threading.Thread):
def __init__(self, threadID, name, cont):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.cont = cont
def run(self):
print "Starting " + self.name +"\n"
print "waiting 2 seconds"
time.sleep(2)
char = getch.getch()
print 'You pressed %s' % char
cont.append(1)
print "Terminating" + self.name
cont = []
thread1 = myThread(1, "Thread1", cont)
thread1.start()
while cont == []:
print "Running"
time.sleep(0.5)
它输出这个:
Starting Thread1
Running
waiting 2 seconds
Running
Running
Running
它会一直呆在那里直到我按下一个键
【问题讨论】:
标签: python multithreading io