当前位置:网站首页>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
- 深度学习笔记 —— 物体检测和数据集 + 锚框
- MySQL uses or to query SQL, and SQL execution is very slow
- Installing kuberneters using kubedm
- Mac 进入mysql终端命令
- On distributed lock
- The difference between static pipeline and dynamic pipeline
- API slow interface analysis
- Locks and transactions in MySQL
猜你喜欢
深度学习笔记 —— 数据增广
深度学习笔记 —— 语义分割和数据集
The applet calls the function of scanning QR code and jumps to the path specified by QR code
A trinomial expression that causes a null pointer
[database] MySQL single table query
The WebService interface writes and publishes calls to the WebService interface (2)
《2021多多阅读报告》发布,95后、00后图书消费潜力攀升
Minimum spanning tree -- unblocked project hdu1863
引入精益管理方式,需要提前做到这九点
Unique primary key ID of tidb sub table -- solution to failure of sequence and Gorm to obtain primary key
随机推荐
The concept of meta universe is popular. Is virtual real estate worth investing
Informatics Aosai yibentong 1212: letters | openjudge 2.5 156: Letters
calendar. Pit point of getactualmaximum (calendar. Day_of_month)
如何在Word中添加漂亮的代码块 | 很全的方法整理和比较
[winui3] write an imitation Explorer file manager
[2022 ICLR] Pyraformer: Low-Complexity Pyramidal Attention for Long-Range 时空序列建模和预测
JS Array常见方法
Chapter I overall project management of information system project manager summary
2022/4/22
Acid of MySQL transaction
Chapter III project schedule management of information system project manager summary
Streamexecutionenvironment of Flink source code
Independent station operation | Facebook marketing artifact - chat robot manychat
机器学习---线性回归
Summary of MySQL knowledge points
Differences between redis and MySQL
QPushbutton 槽函数被多次触发
Use AES encryption - reuse the wisdom of predecessors
configmap
云计算与云原生 — OpenShift 的架构设计