Python 线程池

– Start

点击此处观看本系列配套视频。


我们使用 ThreadPoolExecutor 定义线程池。

任务没有返回值

import threading
import time
from concurrent.futures import ThreadPoolExecutor


def my_task():
    for i in range(3):
        print(f'{threading.current_thread().getName()} - {i}')
        time.sleep(1)


with ThreadPoolExecutor(max_workers = 3) as executor:
    executor.submit(my_task)
    executor.submit(my_task)
    executor.submit(my_task)

任务有返回值

import threading
import time
import random
from concurrent.futures import ThreadPoolExecutor


def my_task():
    r = random.randint(1, 100)
    time.sleep(1)
    print(f'{threading.current_thread().getName()} - {r}')
    return r


with ThreadPoolExecutor(max_workers = 3) as executor:
    future1 = executor.submit(my_task)
    future2 = executor.submit(my_task)
    future3 = executor.submit(my_task)

    # result 会阻塞
    print(future3.result())
    print(future2.result())
    print(future3.result())

数据并行

import threading
from concurrent.futures import ThreadPoolExecutor


def my_task(x):
    print(f'{threading.current_thread().name} - {x}')
    return pow(x, 2)


if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=3) as executor:
        executor.map(my_task, range(100))

– 更多参见:Python 精萃
– 声 明:转载请注明出处
– Last Updated on 2018-10-11
– Written by ShangBo on 2018-10-11
– End

你可能感兴趣的:(Python)