Python中concurrent.futures模块如何使用

说明

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基础教程

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。