[英]python using a thread in an infinite loop
如何使用線程以無限地同時運行2個進程? 我有一個聊天程序,我想輸入打印出來的東西。
我對線程進行了一些研究,看起來真的很復雜。 到目前為止我所擁有的是什么
t = Thread(target=refresh)
t.daemon = True
t.start()
我有一個refresh()函數。
但我很確定這是錯的,我不知道如何在我的輸入旁邊無限地運行它。 有人可以解釋線程是如何工作的,以及我如何能夠無限地運行它與另一個無限循環?
您必須像在代碼中一樣啟動線程。 重要的是等待線程完成(即使它是無限循環)因為沒有它,你的程序將立即停止。 只是用
t.join()
並且你的代碼將運行直到t線程結束。 如果你想要兩個線程,就這樣做
t1.start()
t2.start()
t1.join()
t2.join()
你的兩個線程將同時運行
對於崩潰問題,使用多線程,您必須查看Mutex以獲取IOerror
#!/usr/bin/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"
while 1:
pass
結果是:
Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009
來自: http : //www.tutorialspoint.com/python/python_multithreading.htm
從那里你可以弄清楚如何在線程之間進行交談。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.