当我尝试运行以下代码时,我得到了令人惊讶和冲突的行为.
#include <iostream>
#include <mutex>
int main() {
std::mutex mtx;
std::unique_lock<std::mutex> lock1(mtx);
std::unique_lock<std::mutex> lock2(mtx, std::try_to_lock);
std::cout << "lock1 owns lock: " << lock1.owns_lock() << std::endl;
std::cout << "lock2 owns lock: " << lock2.owns_lock() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
当我在我的计算机上运行它(使用clang ++ 4.0.1或g ++ 7.3.0的linux)时,它打印出两者lock1并lock2拥有锁(令人惊讶).当我运行它时cpp.sh它说它lock1确实拥有,但lock2没有拥有锁(我所期望的).
所有人都使用C++ 11而-Wall没有优化.
我实现了 tonic helloworld教程。然后我尝试更改客户端代码,以便我可以在等待任何请求之前发送多个请求。
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let num_requests = 10;
let mut client = GreeterClient::connect("http://[::1]:50051").await?;
let mut responses = Vec::with_capacity(num_requests);
for _ in 0..num_requests {
let request = tonic::Request::new(HelloRequest {
name: "Tonic".into(),
});
responses.push(client.say_hello(request));
}
for resp in responses {
assert!(resp.await.is_ok());
}
Ok(())
}
Run Code Online (Sandbox Code Playgroud)
这会导致编译错误:
error[E0499]: cannot borrow `client` as mutable more than once at a time
--> src/client.rs:19:24
|
19 | responses.push(client.say_hello(request));
| ^^^^^^ mutable borrow starts here in previous iteration of …Run Code Online (Sandbox Code Playgroud)