在 Python 中启动新线程
pythonserver side programmingprogramming更新于 2025/5/7 4:28:17
要生成另一个线程,您需要调用线程模块 − 中提供的以下方法
thread.start_new_thread ( function, args[, kwargs] )
此方法调用可在 Linux 和 Windows 中快速高效地创建新线程。
方法调用立即返回,子线程启动并使用传递的参数列表调用函数。当函数返回时,线程终止。
这里,args 是一个参数元组;使用空元组调用函数而不传递任何参数。kwargs 是关键字参数的可选字典。
示例
#!/usr/bin/python
import thread
import time
# 为线程定义一个函数
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# 创建两个线程,如下所示
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
尽管对于低级线程来说非常有效,但是与较新的线程模块相比,线程模块的功能非常有限。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

