并发和并行有什么区别?
赞赏的例子.
并发编程和并行编程有什么区别?我问谷歌,但没有找到任何帮助我理解这种差异的东西.你能给我一个例子吗?
现在我发现了这个解释:http://www.linux-mag.com/id/7411 - 但"并发性是程序的属性"vs"并行执行是机器的属性"对我来说还不够 - 我还不能说什么是什么.
并发是在不同的线程上并行运行两个任务.但是,异步方法并行运行,但在同一个线程上运行.这是如何实现的?那么,并行性呢?
这3个概念之间有什么区别?
我注意到Rust没有内置库来处理HTTP,它只有一个net处理原始IP和TCP协议的模块.
我需要获取一个&strURL,发出一个HTTP GET请求,如果成功返回一个String或&str那个对应于HTML或JSON或其他字符串形式的响应.
它看起来像:
use somelib::http;
let response = http::get(&"http://stackoverflow.com");
match response {
Some(suc) => suc,
None => panic!
}
Run Code Online (Sandbox Code Playgroud) 我有一个超 HTTP 请求期货的大向量,并希望将它们解析为结果向量。由于有最大打开文件的限制,我想将并发限制为N个期货。
我已经尝试过,Stream::buffer_unordered但似乎它一个一个地执行期货。
我正在尝试使用hyper来获取HTML页面的内容,并希望同步返回将来的输出。我意识到我可以选择一个更好的示例,因为同步HTTP请求已经存在,但是我对了解我们是否可以从异步计算中返回一个值更感兴趣。
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio;
use futures::{future, Future, Stream};
use hyper::Client;
use hyper::Uri;
use hyper_tls::HttpsConnector;
use std::str;
fn scrap() -> Result<String, String> {
let scraped_content = future::lazy(|| {
let https = HttpsConnector::new(4).unwrap();
let client = Client::builder().build::<_, hyper::Body>(https);
client
.get("https://hyper.rs".parse::<Uri>().unwrap())
.and_then(|res| {
res.into_body().concat2().and_then(|body| {
let s_body: String = str::from_utf8(&body).unwrap().to_string();
futures::future::ok(s_body)
})
}).map_err(|err| format!("Error scraping web page: {:?}", &err))
});
scraped_content.wait()
}
fn read() {
let scraped_content = future::lazy(|| {
let https = HttpsConnector::new(4).unwrap(); …Run Code Online (Sandbox Code Playgroud) I have tried Tokio tasks, but there are no working examples to execute multiple tasks at once. What is wrong with this code?
fn main() {
block_on(speak());
}
async fn speak() {
let hold = vec![say(), greet()];
let results = join_all(hold).await;
}
async fn say() {
println!("hello");
}
async fn greet() {
println!("world");
}
Run Code Online (Sandbox Code Playgroud)
here is the compiler output
error[E0308]: mismatched types
--> sync\src\main.rs:14:27
|
14 | let hold = vec![say(),greet()];
| ^^^^^^^ expected opaque type, found a different opaque …Run Code Online (Sandbox Code Playgroud) 我正在尝试调整Hyper basic 客户端示例以同时获取多个 URL。
这是我目前拥有的代码:
extern crate futures;
extern crate hyper;
extern crate tokio_core;
use std::io::{self, Write};
use std::iter;
use futures::{Future, Stream};
use hyper::Client;
use tokio_core::reactor::Core;
fn get_url() {
let mut core = Core::new().unwrap();
let client = Client::new(&core.handle());
let uris: Vec<_> = iter::repeat("http://httpbin.org/ip".parse().unwrap()).take(50).collect();
for uri in uris {
let work = client.get(uri).and_then(|res| {
println!("Response: {}", res.status());
res.body().for_each(|chunk| {
io::stdout()
.write_all(&chunk)
.map_err(From::from)
})
});
core.run(work).unwrap();
}
}
fn main() {
get_url();
}
Run Code Online (Sandbox Code Playgroud)
它似乎没有同时进行(需要很长时间才能完成),我是否以错误的方式将工作交给了核心?
我正在尝试使用 Rusoto 从存储桶下载文件,并且正在获取文件内容:
fn get_object(client: &TestClient, bucket: &str, filename: &str) {
let get_req = GetObjectRequest {
bucket: bucket.to_owned(),
key: filename.to_owned(),
..Default::default()
};
let result = client.get_object(&get_req).sync().expect("Couldn't GET object");
let stream = result.body.unwrap();
let body = stream.concat2().wait().unwrap();
assert!(body.len() > 0);
}
Run Code Online (Sandbox Code Playgroud)
如何将此GetObjectOutput(result)对象保存到文件中?
我正在学习 Rust,特别是并行的多线程和异步请求。
我阅读了文档,但仍然不明白我在哪里犯了错误。我想我知道在哪里,但不知道如何解决它。
主程序.rs
use std::thread;
struct Request {
url: String,
}
impl Request {
fn new(name: &str) -> Request {
Request {
url: name.to_string(),
}
}
async fn call(&self, x: &str) -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::get(x).await;
Ok(())
}
}
#[tokio::main]
async fn main() {
let requests = vec![
Request::new("https://www.google.com/"),
Request::new("https://www.google.com/"),
];
let handles: Vec<_> = requests
.into_iter()
.map(|request| {
thread::spawn(move || async {
request.call(&request.url).await;
})
})
.collect();
for y in handles {
println!("{:?}", y);
} …Run Code Online (Sandbox Code Playgroud) 我正在查看这个示例,以便在 Rust 中同时下载内容。
粗略地说,它看起来像这样:
#![feature(async_closure)]
use futures::{stream, StreamExt}; // 0.3.13
async fn foo() {
let xs_new = stream::once(async { 42 })
.map(async move |x| {
Some(x + 1)
})
.buffer_unordered(42);
}
Run Code Online (Sandbox Code Playgroud)
但是,我希望用来filter_map做这样的事情:
#![feature(async_closure)]
use futures::{stream, StreamExt}; // 0.3.13
async fn foo() {
let xs_new = stream::once(async { 42 })
.filter_map(async move |x| if x % 2 == 0 { Some(x + 1) } else { None })
.buffer_unordered(42);
}
Run Code Online (Sandbox Code Playgroud)
然而,这会失败并出现错误:“{integer} 不是 Future,该特征...未针对 {integer} 实现”。
有谁知道为什么filter_map …
我正在学习使用Rust期货,并且感到非常困惑。我觉得我太傻了,但是当会then,and_then和or_else使用吗?期望什么返回类型?
请提供一些您希望看到的不同情况的示例。
rust ×9
rust-tokio ×4
concurrency ×3
async-await ×2
future ×2
hyper ×2
amazon-s3 ×1
asynchronous ×1
file ×1
get ×1
http ×1
reqwest ×1
rusoto ×1