品易云推流 关闭
文章详情页
文章 > Python基础教程 > python多线程中的threading使用技巧

python多线程中的threading使用技巧

头像

十一

2020-11-17 15:56:532535浏览 · 0收藏 · 0评论

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

threading模块的主要应用:

多线程启动

# 多线程启动
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

同步开启多线程

# 同步开启多线程
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())

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

关注

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

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

底部广告图