use futures::executor::block_on;
asyncfnhello_world() {
println!("hello, world!");
}
fnmain() {
let future = hello_world(); // Nothing is printed
block_on(future); // `future` is run and "hello, world!" is printed
}
import requests
from timer import timer
URL = 'https://httpbin.org/uuid'deffetch(session, url):with session.get(url) as response:
print(response.json()['uuid'])
@timer(1, 1)defmain():with requests.Session() as session:
for _ inrange(100):
fetch(session, URL)
进程/线程/协程性能比较
多进程:7秒
from multiprocessing.pool import Pool
import requests
from timer import timer
URL = 'https://httpbin.org/uuid'deffetch(session, url):with session.get(url) as response:
print(response.json()['uuid'])
@timer(1, 1)defmain():with Pool() as pool:
with requests.Session() as session:
pool.starmap(fetch, [(session, URL) for _ inrange(100)])
进程/线程/协程性能比较
线程:4秒
from concurrent.futures import ThreadPoolExecutor
import requests
from timer import timer
URL = 'https://httpbin.org/uuid'deffetch(session, url):with session.get(url) as response:
print(response.json()['uuid'])
@timer(1, 1)defmain():with ThreadPoolExecutor(max_workers=100) as executor:
with requests.Session() as session:
executor.map(fetch, [session] * 100, [URL] * 100)
executor.shutdown(wait=True)
进程/线程/协程性能比较
协程:2秒
...
URL = 'https://httpbin.org/uuid'asyncdeffetch(session, url):asyncwith session.get(url) as response:
json_response = await response.json()
print(json_response['uuid'])
asyncdefmain():asyncwith aiohttp.ClientSession() as session:
tasks = [fetch(session, URL) for _ inrange(100)]
await asyncio.gather(*tasks)
@timer(1, 1)deffunc():
asyncio.run(main())
fnmain() {
let listener = TcpListener::bind("127.0.0.1:8080").unwrap(); // bind listenerlet pool = ThreadPool::new(100); // same number as max concurrent requestsletmut count = 0; // count used to introduce delays// listen to all incoming request streamsfor stream in listener.incoming() {
let stream = stream.unwrap();
count = count + 1;
pool.execute(move || {
handle_connection(stream, count); // spawning each connection in a new thread
});
}
}
#### Concept of Future
* Three phases in asynchronous task:
1. **Executor**: A Future is **polled** which result in the task progressing
- Until a point where it can no longer make progress
2. **Reactor**: Register an **event source** that a Future is waiting for
- Makes sure that it will wake the Future when event is ready
3. **Waker**: The event happens and the Future is **woken up**
- Wake up to the executor which polled the Future
- Schedule the future to be polled again and make further progress
---