写一个python的concurrent.futures线程池的demo

bluesky1年前 ⋅ 930 阅读
以下是一个使用 "concurrent.futures" 模块的 Python 线程池示例。它将创建两个线程以并行地执行两个任务,并在它们完成后关闭线程池。

```python
import concurrent.futures
import time

def task_one():
    print("Starting task one...")
    time.sleep(2)
    print("Task one completed.")
    return "Result of task one"

def task_two():
    print("Starting task two...")
    time.sleep(4)
    print("Task two completed.")
    return "Result of task two"

if __name__ == "__main__":
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
        future_one = executor.submit(task_one)
        future_two = executor.submit(task_two)

        results = [future_one.result(), future_two.result()]
        
        print("Results of two tasks: {}".format(results))
```

输出结果:

```
Starting task one...
Starting task two...
Task one completed.
Task two completed.
Results of two tasks: ['Result of task one', 'Result of task two']
```

该示例使用"concurrent.futures.ThreadPoolExecutor()"创建一个具有最大工作线程数为 2 的线程池,并向其提交两个任务。将每个任务的返回值保存在一个列表中,并在任务完成后打印出它们的结果。

注:在此示例中,我们使用了"if __name__ == "__main__":",这是一个约定,以确保Python解释器只会通过该代码运行一次,并且仅当文件作为主模块被运行时才运行代码。

全部评论: 0

    相关推荐