Iv4*_*v4n 0 compression encryption asynchronous rust rust-tokio
在我的理解中,异步只能处理I/O密集型任务,例如读写套接字或文件,而无法处理CPU密集型任务,例如加密和压缩。
所以在 Rust Tokio Runtime 中,我认为只需要用来spawn_blocking处理 CPU 密集型任务。但我看过这个回购协议,例子是
#[tokio_02::main]
async fn main() -> Result<()> {
let data = b"example";
let compressed_data = compress(data).await?;
let de_compressed_data = decompress(&compressed_data).await?;
assert_eq!(de_compressed_data, data);
println!("{:?}", String::from_utf8(de_compressed_data).unwrap());
Ok(())
}
Run Code Online (Sandbox Code Playgroud)
该库在压缩和异步 I/O 类型之间创建适配器。
我有 3 个问题:
等待压缩/解压缩的目的是什么?
这些适配器是必要的还是我对异步的理解错误?
我可以直接在 Tokio 多线程运行时进行压缩操作吗?像这样
async fn foo() {
let mut buf = ...;
compress_sync(&mut buf);
async_tcp_stream.write(buf).await;
}
Run Code Online (Sandbox Code Playgroud)
In my understanding, asynchronous can only handle I/O intensive tasks such as reading and writing sockets or files, but can do nothing with CPU intensive tasks such as encryption and compression.
This is misguided. Asynchronous constructs are designed to work with non-blocking operations, irrespective of what kinds of resources are involved underneath. For instance, a future which delegates computation to a separate thread would be a valid use of async/await.
话虽如此,异步压缩之所以有用,是因为它们公开了I/O 适配器,这些适配器也可以在异步编程中工作。尽管这些压缩算法主要受 CPU 限制,但它们是从任意读取器或写入器馈送的批量工作,这意味着该过程可能必须等待 I/O 执行。
例如,请参阅文档bufread::ZstdDecoder
该结构实现一个
AsyncRead接口,将从底层流中读取压缩数据并发出未压缩数据流。
这是同步字节源适配器(例如flate2::bufread::GzDecoder. 即使您只使用一个compress函数,它的同步版本也会在等待读取或写入数据的可能性时被阻塞。
也可以看看:
| 归档时间: |
|
| 查看次数: |
215 次 |
| 最近记录: |