在无限循环中使用线程的Python
我想知道怎么用线程来同时无限运行两个进程。我有一个聊天程序,想在输入的同时还能看到输出。
我查了一些关于线程的资料,感觉真的很复杂。目前我有的代码是:
t = Thread(target=refresh)
t.daemon = True
t.start()
我有一个叫refresh()的函数。
但我觉得这可能不对,我也不知道怎么让它和我的输入同时无限运行。能不能有人解释一下线程是怎么回事,以及我该怎么让它和另一个无限循环一起运行?
2 个回答
2
#!/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
从这个链接你可以了解线程之间是怎么交流的等等。
2
你需要像在代码中那样启动你的线程。重要的是要等线程完成(即使它是个无限循环),因为如果不这样做,你的程序会立刻停止。
t.join()
这样你的代码就会一直运行,直到线程结束。如果你想要两个线程,只需这样做:
t1.start()
t2.start()
t1.join()
t2.join()
这样你的两个线程就会同时运行。
关于你崩溃的问题,在多线程的情况下,你需要了解一下互斥锁(Mutex),这和输入输出错误有关。