
thread方法对创建线程有效且直接。您可以在Linux和Windows中运行程序。
1、thread方法启动了新的线程,并返回了它的识别符。
该系统将使用传输的参数列表调用指定为函数参数的函数。 function 返回时线程会静默退出。
2、Args是参数元组,使用空元组调用function不带参数。
可选参数指定关键词参数的字典。
1 2 | #语法
thread.start_new_thread ( function , args[, kwargs] )
|
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #Python 多线程示例。
#1. 使用递归计算阶乘。
#2. 使用线程调用阶乘函数。
from _thread import start_new_thread
from time import sleep
threadId = 1 #线程计数器
waiting = 2 #2秒等待的时间
def factorial(n):
global threadId
rc = 0
if n < 1: # base case
print( "{}: {}" .format( '\nThread' , threadId ))
threadId += 1
rc = 1
else :
returnNumber = n * factorial( n - 1 ) # recursive call
print( "{} != {}" .format(str(n), str(returnNumber)))
rc = returnNumber
return rc
start_new_thread(factorial, (5, ))
start_new_thread(factorial, (4, ))
print( "Waiting for threads to return..." )
sleep(waiting)
|
以上就是python thread模块创建线程,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。