概述

通常,在写任务调度的时候,难免遇到使用多线程、多进程、线程池、进程池的场景。下边以ThreadPoolExecutor线程池为例,记录一下使用方法,其他类似,废话不多说,直接看代码

# -*- coding:utf-8 -*-
import time
import random
from concurrent.futures import ThreadPoolExecutor, as_completed, wait, FIRST_COMPLETED, ALL_COMPLETED


class ThreadPool (object):
    def __init__(self):
        pass

    def get_data(self, task_id):
        sleep = random.randint (1, 10)
        time.sleep (sleep)
        return sleep

    def start(self):
        all_code = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        executor = ThreadPoolExecutor (4)
        all_task = [executor.submit (self.get_data, code) for code in all_code]
        wait (all_task, return_when=FIRST_COMPLETED)
        for future in as_completed (all_task):
            data = future.result ()
            print (data)

    def run(self):
        self.start ()


if __name__ == '__main__':
    tp = ThreadPool ()
    tp.run ()
GitHub 加速计划 / th / ThreadPool
7.74 K
2.22 K
下载
A simple C++11 Thread Pool implementation
最近提交(Master分支:2 个月前 )
9a42ec13 - 9 年前
fcc91415 - 9 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐