前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python批量启动多线程

python批量启动多线程

作者头像
机器学习和大数据挖掘
发布2019-07-02 09:21:49
1.2K0
发布2019-07-02 09:21:49
举报
文章被收录于专栏:数据挖掘数据挖掘

还未了解多线程的请查看博文 python3多线程趣味详解

python3多线程趣味详解 只是介绍了 python 多线程的使用,对于批量启动线程来说有些不适用,于是出现如下方法:

建立一个线程池,并将某个线程放入进去

代码语言:javascript
复制
threadpool = []
th = threading.Thread(target=func_name, args=func_args)
threadpool.append(th)

批量加入线程

代码语言:javascript
复制
for i in range(10):
    th = threading.Thread(target=func_name, args=func_args)
    threadpool.append(th)

批量开始线程

代码语言:javascript
复制
for th in threadpool:
        th.start()
for th in threadpool:
    threading.Thread.join(th)

实例如下:

代码语言:javascript
复制
#!/usr/bin/python3.4
# -*- coding: utf-8 -*-

import time
import threading


def matter1(music, test):
    print test, music
    # 假设每一首歌曲的时间是2秒
    time.sleep(2)


if __name__ == '__main__':
    # 设定我要听的歌为
    musics = ["music1", "music2", "music3"]
    test = "122678"
    # 开始时间
    start = time.time()

    threadpool = []

    for music in musics:
        th = threading.Thread(target=matter1, args=(music, test))
        threadpool.append(th)
    for th in threadpool:
        th.start()
    for th in threadpool:
        threading.Thread.join(th)

    # 结束时间
    end = time.time()
    print("完成的时间为:" + str(end - start))

完成同时听三首歌线程,花费时间 2s:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-04-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档