• 技术文章 >Python技术 >Python基础教程

    python thread模块创建线程

    小妮浅浅小妮浅浅2021-08-30 09:18:50原创2535

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

    专题推荐:python thread模块
    上一篇:python用户如何自定义异常 下一篇:python threading实现线程的过程

    相关文章推荐

    • python中socket建立客户连接• python中Roberts算子是什么• python中Prewitt算子如何理解• python中Sobel算子是什么• python中Sobel算子如何使用• python中Laplacian算子如何使用• python中Laplacian算子是什么• python输入函数input的使用• python控制语句的两大分类• python编写程序的常见错误• python用户如何自定义异常

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网