首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Python3-多线程使用,就这么简单

前言

多个任务可以由多个进程完成,也可以由一个进程多个线程来完成。Python2标准库中提供了两个模块支持多线程,thread和threading。其中,threading是对thread的封装,thread有一些缺点在threading有了补充;在Python3中推荐直接使用threading,弃用了thread。

threading模块

简单例子

import threading

import time

def thread_print(i):print(i);time.sleep(i//10);print(i,"end")

threads = []

#创建线程对象

for i in range(100):threads.append(threading.Thread(target=thread_print,args=(i,)))

#运行线程

for th in threads:th.start()

#等待线程退出

for th in threads:th.join()

print("finished")

步骤:

1、创建Thread对象,参数为函数名,和参数元组;

2、使用start()方法执行线程;

3、使用join()函数等待线程退出,如果不等待线程退出,finished这行就会在线程结束之前就打印出来。

总结

人生苦短,我用Python!就这么简单。

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20181114A1X2I700?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券