您现在的位置是:课程教程文章

Python中concurrent.futures模块如何使用

2023-12-14 20:43课程教程文章 人已围观

说明

1、标准库为我们提供了concurrent.futures模块,它提供了线程池和进程池两个类。

2、该模块通过submit返回的是一个future对象。

它是一个未来可期的对象,通过它可以获悉线程的状态主线程(或进程)中可以获取某一个线程(进程)执行的状态或者某一个任务执行的状态及返回值。

实例

importflask
importjson
importtime
fromconcurrent.futuresimportThreadPoolExecutor#需安装

app=flask.Flask(__name__)
pool=ThreadPoolExecutor()


defread_file():
time.sleep(0.1)
return"fileresult"


defread_db():
time.sleep(0.2)
return"dbresult"


defread_api():
time.sleep(0.3)
return"apiresult"


@app.route("/")
defindex():
result_file=pool.submit(read_file)
result_db=pool.submit(read_db)
result_api=pool.submit(read_api)

returnjson.dumps({
"result_file":result_file.result(),
"result_db":result_db.result(),
"result_api":result_api.result(),
})


if__name__=="__main__":
app.run()

以上就是Python中concurrent.futures模块的使用,希望对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

课程教程:Python中concurrent.futures模块如何使用

上一篇:Python kmeans聚类的使用

下一篇:没有了

站点信息

  • 文章统计篇文章