python在无限循环中使用线程

2024-04-24 15:04:03 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用线程来无限期地同时运行两个进程?我有一个聊天程序,我想输入的同时有东西打印出来。在

我对线程做了一些研究,看起来很复杂。我现在有什么

t = Thread(target=refresh)    
t.daemon = True
t.start()

我有一个refresh()函数。在

但我很确定这是错误的,我不知道如何在我的输入之外无限地运行它。有人能解释线程是如何工作的,以及我如何在另一个无限循环的同时无限地运行它?在


Tags: 函数程序truetarget进程错误线程thread
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

其结果是:

^{pr2}$

发件人:http://www.tutorialspoint.com/python/python_multithreading.htm

从那里你可以知道如何在线程之间进行对话。在

你必须像在代码中那样启动线程。 即使没有无限循环,线程也会立即停止,因为这很重要。 就用吧

t.join()

你的代码会一直运行到t线程结束。如果你想要两条线,就这样做

^{pr2}$

你的两个线程将同时运行

对于崩溃问题,对于多线程,您必须查看Mutex中的IOerror

相关问题 更多 >