Python--多线程处理

python中有好几种多线程处理方式,更喜欢使用isAlive()来判断线程是否存活,笔记一下,供以后查找

复制代码
# coding: utf-8
import sys, time
import threading


def split_list_item_to_group(item_list, group_count):
    """
    将传入的List中的元素拆分到多个List中,再将这些List作为一个List返回
    :param item_list:
    :param group_count:
    :return:
    """
    item_group_list = list()
    for n in range(0, group_count):
        item_group_list.append(list())
    for num in range(0, len(item_list)):
        mod_num = num % group_count
        item_group_list[mod_num].append(item_list[num])
    return item_group_list


def print_number_with_thread(thread_paras):
    number_group = thread_paras["number_group"]
    for number in number_group:
        print("number is {0}".format(number))
        time.sleep(0.1)


def demo():
    number_list = list()
    thread_count = 10
    thread_list = list()
    for number in range(0, 100000):
        number_list.append(number)
    number_group_list = split_list_item_to_group(number_list, thread_count)
    for number_group in number_group_list:
        thread_paras = {
            "number_group": number_group,
        }
        thread_item = threading.Thread(target=print_number_with_thread, args=(thread_paras,))
        thread_list.append(thread_item)
        thread_item.start()
    running_thread_count = thread_count
    while running_thread_count > 0:
        running_thread_count = len(filter(lambda item: item.isAlive(), thread_list))
        print("正在运行的线程数:{0}".format(running_thread_count))
        time.sleep(1)
    print("多线程执行完成")


demo()
复制代码

 

在使用threading.Thread创建线程时,对传入的第一个参数有类型要求,为图方便,可以直接要传入的参数封装到一个dict中作为线程参数,然后在线程方法内部转换下。

=====================================================

posted on   笑东风  阅读(913)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现

导航

点击右上角即可分享
微信分享提示