zoukankan      html  css  js  c++  java
  • 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中作为线程参数,然后在线程方法内部转换下。

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

  • 相关阅读:
    windows7通过Dns.GetHostAddresses(Dns.GetHostName())获得ipv6地址转换到ipv4
    题解 P3829 【[SHOI2012]信用卡凸包】
    点积与叉积
    点分治
    珂朵莉树
    NOIP2020模拟赛(二十五)7.26 结题报告
    树连剖分
    NOIP2020模拟赛(拾)解题报告
    题解 P2538 【[SCOI2008]城堡】
    模拟退火
  • 原文地址:https://www.cnblogs.com/TeyGao/p/6617073.html
Copyright © 2011-2022 走看看