我有一個(gè)函數(shù)foo,只有在滿足條件后才會(huì)停止.當(dāng)foo正在運(yùn)行時(shí),我需要一直詢問用戶輸入(不斷詢問用戶輸入).我希望它們分開運(yùn)行而不會(huì)相互干擾.
在下面的示例中,foo繼續(xù)打印’Hello’并且getUserInput繼續(xù)查找用戶輸入.即使我沒有為用戶輸入輸入任何內(nèi)容,我也希望foo繼續(xù)打印你好.只要用戶沒有輸入字母’e’,它就會(huì)一直詢問輸入.我有以下嘗試:
import threading
from time import sleep
class test:
def __init__(self):
self.running = True
def foo(self):
while(self.running):
print 'Hello\n'
sleep(2)
def getUserInput(self):
x = ''
while(x != 'e'):
x = raw_input('Enter value: ')
self.running = False
def go(self):
th1 = threading.Thread(target=self.foo)
th2 = threading.Thread(target=self.getUserInput)
th1.start()
th2.start()
t = test()
t.go()
我的代碼打印出第一個(gè)問候語并要求輸入,但之后沒有任何內(nèi)容.我究竟做錯(cuò)了什么?感謝您的幫助. 解決方法: 更新:開啟者在IDLE上的Windows上運(yùn)行他的代碼.關(guān)于I / O,它的行為與shell或Windows命令行不同.他的代碼適用于Windows命令行.
原則上,您的代碼適合我.我正在運(yùn)行Python 2.6.5.
這里有幾條評(píng)論:
1)在你的情況下,只有兩個(gè)線程是好的:主線程和另一個(gè)線程.但是,它也可以使用三個(gè).只是你的主線程只是等待其他線程完成.
2)你應(yīng)該明確地加入()你產(chǎn)生的所有線程.您在終止它之前在主線程中執(zhí)行此操作.記錄你產(chǎn)生的線程(例如在列表線程中),然后在程序結(jié)束時(shí)加入它們(例如,對(duì)于線程中的t:t.join()).
3)您在線程之間共享變量self.running.在這種情況下它很好,因?yàn)橐粋€(gè)線程只讀取它而另一個(gè)只寫它.通常,您需要非常小心共享變量并在更改之前獲取鎖定.
4)您應(yīng)該在主線程中捕獲KeyboardInterrupt異常,并找到一種方法與您的其他線程進(jìn)行通信以終止:)
5)使用小寫方法名稱,因此不是getUserInput,而是調(diào)用get_user_input.使用大寫的類名并從object繼承:class Test(object):
這是一個(gè)運(yùn)行的例子:
import threading
from time import sleep
def main():
t = Test()
t.go()
try:
join_threads(t.threads)
except KeyboardInterrupt:
print "\nKeyboardInterrupt catched."
print "Terminate main thread."
print "If only daemonic threads are left, terminate whole program."
class Test(object):
def __init__(self):
self.running = True
self.threads = []
def foo(self):
while(self.running):
print '\nHello\n'
sleep(2)
def get_user_input(self):
while True:
x = raw_input("Enter 'e' for exit: ")
if x.lower() == 'e':
self.running = False
break
def go(self):
t1 = threading.Thread(target=self.foo)
t2 = threading.Thread(target=self.get_user_input)
# Make threads daemonic, i.e. terminate them when main thread
# terminates. From: https:///a/3788243/145400
t1.daemon = True
t2.daemon = True
t1.start()
t2.start()
self.threads.append(t1)
self.threads.append(t2)
def join_threads(threads):
"""
Join threads in interruptable fashion.
From https:///a/9790882/145400
"""
for t in threads:
while t.isAlive():
t.join(5)
if __name__ == "__main__":
main()
鍵入e或E時(shí),程序會(huì)在短暫延遲后結(jié)束(按照您的意圖).按ctrl c時(shí),它會(huì)立即終止.制作一個(gè)使用線程響應(yīng)異常的程序比預(yù)期的要復(fù)雜一些.我在上面的源代碼中包含了重要的參考資料.
這是它在運(yùn)行時(shí)的樣子:
$python supertest.py
Hello
Enter 'e' for exit:
Hello
Hello
Hello
e
$
來源:http://www./content-1-216201.html
|