品易云推流 关闭
文章详情页
文章 > Python基础教程 > python thread模块创建线程

python thread模块创建线程

Python thread模块

头像

小妮浅浅

2021-08-30 09:18:502314浏览 · 0收藏 · 0评论

thread方法对创建线程有效且直接。您可以在Linux和Windows中运行程序。

1、thread方法启动了新的线程,并返回了它的识别符。

该系统将使用传输的参数列表调用指定为函数参数的函数。 function 返回时线程会静默退出。

2、Args是参数元组,使用空元组调用function不带参数。

可选参数指定关键词参数的字典。

#语法
thread.start_new_thread ( function, args[, kwargs] )

实例

#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电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图