当前位置:网站首页>Collaboration future object and concurrent futures
Collaboration future object and concurrent futures
2022-04-23 05:14:00 【zzzzls~】
List of articles
Future object
Future Is a special low-level waiting object (Task yes Future Subclasses of ), Represents the end result of an asynchronous operation
When one Future The object is waiting , This means that the process will remain waiting until Future Object has been operated elsewhere
async def main():
# Get the current event loop
loop = asyncio.get_running_loop()
# Create a task (Future object ), No behavior is bound by default , Then the task will never end
fut = loop.create_futute()
# Wait until the final result of the task (Future object ), If there is no result, you will wait all the time
await fut
import asyncio
async def set_after(fut):
await asyncio.sleep(2)
fut.set_result('666')
async def main():
loop = asyncio.get_running_loop()
fut = loop.create_future()
# Create a task , The binding set_after function , The function is inside 2s after , Will give fut assignment
# Manual settings future The end result of the mission , that fut And that's it
await loop.create_task(set_after(fut))
data = await fut
print(data)
asyncio.run(main())
Future The object itself has no function binding , Want to loop events to get Future Result , You need to set it manually
Task Object inheritance Future Object and extended , It can be implemented after the execution of the corresponding bound function , Automatic execution set_result
, In order to achieve automatic end
concurrent.futures
stay python Of concurrent.futures
There is also one in the module Future object , This object is used to implement asynchronous operation based on thread pool or process pool
import time
from concurrent.futures import Future
from concurrent.futures.thread import ThreadPoolExecutor
def func(value):
time.sleep(1)
print(value)
pool = ThreadPoolExecutor(max_workers=5)
for i in range(1):
fut = pool.submit(func, i)
print(fut)
Example : async + requests
(1) Use it directly , The actual form is synchronous request
import asyncio
import requests
async def send_req(url):
print(f' To request {
url}')
res = requests.get(url).text
print(res)
print(f' End of request {
url}')
return res
async def main():
tasks = [
asyncio.create_task(send_req('http://httpbin.org/ip')),
asyncio.create_task(send_req('http://httpbin.org/headers')),
]
await asyncio.wait(tasks)
asyncio.run(main())
(2) run_in_executor Asynchronous requests
import asyncio
import requests
import concurrent.futures
def send_req(url):
print(f' To request {
url}')
res = requests.get(url).text
print(res)
print(f' End of request {
url}')
return res
async def main():
loop = asyncio.get_running_loop()
# None, By default ThreadPoolExecutor Thread pool
# First step : Internal will call first ThreadPoolExecutor Of submit Method to apply for a thread to execute in the thread pool send_req function , And return a concurrent.futures.Future object
# The second step : call asyncio.wrap_future take concurrent.futures.Future The object is packaged as asycio.Future object
tasks = [
loop.run_in_executor(None, send_req, 'http://httpbin.org/ip'),
loop.run_in_executor(None, send_req, 'http://httpbin.org/headers')
]
await asyncio.wait(tasks)
# concurrent.futures asynchronous
async def main():
loop = asyncio.get_running_loop()
with concurrent.futures.ThreadPoolExecutor() as pool:
tasks = [
loop.run_in_executor(pool, send_req, 'http://httpbin.org/ip'),
loop.run_in_executor(pool, send_req, 'http://httpbin.org/user-agent'),
]
await asyncio.wait(tasks)
asyncio.run(main())
When a project is developed with asynchronous programming of a co program , If you want to use a third-party module , When the third-party module does not support asynchronous programming in CO programming mode , You can use this function
版权声明
本文为[zzzzls~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220547252170.html
边栏推荐
- Introduction to load balancing
- Flip coin (Blue Bridge Cup)
- Various ways of writing timed tasks of small programs
- Chapter II project scope management of information system project manager summary
- Independent station operation | Facebook marketing artifact - chat robot manychat
- Tensorflow realizes web face login system
- 信息学奥赛一本通 1212:LETTERS | OpenJudge 2.5 156:LETTERS
- On distributed lock
- MySQL views the SQL statement details executed by the optimizer
- calendar. Pit point of getactualmaximum (calendar. Day_of_month)
猜你喜欢
[2021] Spatio-Temporal Graph Contrastive Learning
Servlet3 0 + event driven for high performance long polling
Summary of MySQL knowledge points
Redis data type usage scenario
直播带货表格模板-自动显示图片-自动关联系列商品
独立站运营 | FaceBook营销神器——聊天机器人ManyChat
Restful toolkit of idea plug-in
2022年最热门的招聘技术技能是什么,您绝对想不到
Jupyter notebook crawling web pages
数字化转型失败,有哪些原因?
随机推荐
Chapter I overall project management of information system project manager summary
Unity C# 网络学习(四)
How does PostgreSQL parse URLs
Good simple recursive problem, string recursive training
Tensorflow realizes web face login system
Swing display time (click once to display once)
Details related to fingerprint payment
机器学习---线性回归
退出vim的方法
Unity C e-learning (IV)
Leetcode -- heuristic search
如何在Word中添加漂亮的代码块 | 很全的方法整理和比较
[2021] Spatio-Temporal Graph Contrastive Learning
[2021] Spatio-Temporal Graph Contrastive Learning
《2021多多阅读报告》发布,95后、00后图书消费潜力攀升
Streamexecutionenvironment of Flink source code
Flip coin (Blue Bridge Cup)
At pgconf Asia Chinese technology forum, listen to Tencent cloud experts' in-depth understanding of database technology
MySQL views the SQL statement details executed by the optimizer
Summary of R & D technology