Python 使用线程池并行任务

记录一下最近写的——用 Python 线程池来并行生成数据 

from tqdm import tqdm
from concurrent.futures import ThreadPoolExecutor, as_completed

# 使用线程池并行生成数据
max_workers = min(64, remaining_count)  # 限制最大线程数
print(f"使用 {max_workers} 个线程并行生成数据")

with ThreadPoolExecutor(max_workers=max_workers) as executor:
    # 提交所有任务
    future_to_index = {
        executor.submit(generate_data): i #generate_data 这里写需要运行的任务函数名
        for i in range(remaining_count)
    }
    
    # 使用tqdm显示进度
    with tqdm(total=remaining_count, desc="生成进度", unit="条") as pbar:
        for future in as_completed(future_to_index):
            result = future.result()
            if result:
                dataset.append(result)
            pbar.update(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值