要生成另一个线程,您需要调用线程模块中可用的以下方法-
thread.start_new_thread ( function, args[, kwargs] )
通过此方法调用,可以快速有效地在Linux和Windows中创建新线程。
方法调用立即返回,子线程启动,并使用传递的args列表调用函数。当函数返回时,线程终止。
在这里,args是参数的元组;使用一个空的元组调用函数而不传递任何参数。kwargs是关键字参数的可选字典。
#!/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
尽管它对于低级线程非常有效,但是与更新的线程模块相比,线程模块非常有限。