• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python多任务编程多线程的使用

python 搞代码 3年前 (2022-03-30) 37次浏览 已收录 0个评论

1.导入线程包

import threading

在 CPython 中,因为存在 全局解释器锁,同一时刻只有一个线程能够执行 Python 代码(尽管某些性能导向的库可能会去除此限度)。 如果你想让你的利用更好地利用多外围计算机的计算资源,举荐你应用 multiprocessing 或 concurrent.futures.ProcessPoolExecutor。 然而,如果你想要同时运行多个 I/O 密集型工作,则多线程依然是一个适合的模型。

2.创立线程

threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

group: 为当前的ThreadGroup类预留

name 为线程名字,个别不必设置

target: 被执行的对象,由run()办法执行

args: target元组传参

kwargs:target字典传参

daemon: 是否为守护过程

demo1_process = threading.Thread(target = dance)
demo2_process = threading.Thread(target = sing)
#3.启动线程

罕用办法:应用start办法
dance_process.start()
sing_process.start()

4.代码实现

#导入线程模块
import threading
import time

def dance():
    for i in range(3):
        print("dance...")
        time.sleep(0.5)

def sing():
    for i in range(3):
        print("sing...")
        time.sleep(0.5)



if __name__ == "__main__":
#创立线程    
    dance_process=threading.Thread(target=dance)
    sing_process=threading.Thread(target=sing)
#启动线程
    dance_process.start()
    sing_process.start()

运行后果:


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python多任务编程多线程的使用

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址