python threading线程数

发布时间 2023-11-27 15:29:04作者: 公子Learningcarer
import threading
import time

name_list = [
    {"李四1": 1234556},
    {"李四2": 1234556},
    {"李四3": 1234556},
    {"李四4": 1234556},
    {"李四5": 1234556},
    {"李四6": 1234556},
    {"李四7": 1234556},
    {"李四8": 1234556},
    {"李四9": 1234556},
]

batch_size = len(name_list) // 3  # 计算每个批次的条数,这里我们选择将任务分为3个批次


def process_data(data):
    # 这里写处理数据的代码,例如打印数据
    for i in data:
        for name, value in i.items():
            print(f"Processing {name}: {value}")

    # 使用线程池并行执行每个批次的任务


threads = []
for i in range(batch_size):
    # 从name_list中提取当前批次的条目(列表切片)
    batch = name_list[i * batch_size:(i + 1) * batch_size]
    # 创建线程并提交给线程池执行
    thread = threading.Thread(target=process_data, args=(batch,))
    threads.append(thread)
    print('------------------------------')
    print(time.time())
    thread.start()

# 等待所有线程执行完毕
for thread in threads:
    thread.join()