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

    python多线程中的threading使用技巧

    十一十一2020-11-17 15:56:53原创2324

    任何一个区域设定里总归是有一个掌控大局的管理者,这跟我们在公司里,需要一个领导统筹布局是一样的道理,那在python多线程里,也有一个这么重要角色的方法——threading,相信大家也不少见过吧,那大家知道关于这个方法实用的功能有哪些吗?为什么大家都选择它?还理解认知不清楚的,可以继续往下看文。

    threading模块的主要应用:

    多线程启动

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    # 多线程启动

    import os

    import time

    from threading import Thread

      

    def func():

        time.sleep(1)

        print('hello 线程', os.getpid())

      

    t = Thread(target=func)

    t.start()

    print(os.getpid())

      

    # 结果

    # 6360

    # hello 线程 6360

    同步开启多线程

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    # 同步开启多线程

    import os

    import time

    from threading import Thread

      

    def func():

        time.sleep(1)

        print('hello 线程', os.getpid())

    thread_l = []

    for i in range(10):

        t = Thread(target=func)

        t.start()

        thread_l.append(t)

    for j in thread_l:

        j.join()

    print(os.getpid())

    大家如果在碰到需要多线程运转开启的时候,直接调用这个模块,演示代码在上述给大家均已提供,如果还需要代码解说,直接套用上述内容即可。

    专题推荐:python多线程中的threading使用
    上一篇:怎么使用python脚本实现表格打印? 下一篇:python多线程中锁怎么使用?

    相关文章推荐

    • 如何使用Python实现文件压缩?• 什么是Python的回调函数?• 怎么使用python脚本实现表格打印?

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网