sync: Make Lock more similar to std::sync::Mutex (#1573)

This renames `Lock` to `Mutex`, and brings the API more in line with `std::sync::Mutex`.

In partcular, locking now only takes `&self`, with the expectation that you place the `Mutex` in an `Arc` (or something similar) to share it between threads.

Fixes #1544.
Part of #1210.
This commit is contained in:
Jon Gjengset
2019-09-19 11:46:52 -04:00
committed by GitHub
parent d1f60ac4c6
commit e3415d8d61
6 changed files with 168 additions and 195 deletions
+9 -6
View File
@@ -27,12 +27,15 @@
#![warn(rust_2018_idioms)]
use futures::{Poll, SinkExt, Stream, StreamExt};
use std::{collections::HashMap, env, error::Error, io, net::SocketAddr, pin::Pin, task::Context};
use std::{
collections::HashMap, env, error::Error, io, net::SocketAddr, pin::Pin, sync::Arc,
task::Context,
};
use tokio::{
self,
codec::{Framed, LinesCodec, LinesCodecError},
net::{TcpListener, TcpStream},
sync::{mpsc, Lock},
sync::{mpsc, Mutex},
};
#[tokio::main]
@@ -42,7 +45,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
// The server task will hold a handle to this. For every new client, the
// `state` handle is cloned and passed into the task that processes the
// client connection.
let state = Lock::new(Shared::new());
let state = Arc::new(Mutex::new(Shared::new()));
let addr = env::args().nth(1).unwrap_or("127.0.0.1:6142".to_string());
@@ -58,7 +61,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let (stream, addr) = listener.accept().await?;
// Clone a handle to the `Shared` state for the new connection.
let state = state.clone();
let state = Arc::clone(&state);
// Spawn our handler to be run asynchronously.
tokio::spawn(async move {
@@ -129,7 +132,7 @@ impl Shared {
impl Peer {
/// Create a new instance of `Peer`.
async fn new(
mut state: Lock<Shared>,
state: Arc<Mutex<Shared>>,
lines: Framed<TcpStream, LinesCodec>,
) -> io::Result<Peer> {
// Get the client socket address
@@ -184,7 +187,7 @@ impl Stream for Peer {
/// Process an individual chat client
async fn process(
mut state: Lock<Shared>,
state: Arc<Mutex<Shared>>,
stream: TcpStream,
addr: SocketAddr,
) -> Result<(), Box<dyn Error>> {
+2 -2
View File
@@ -9,9 +9,9 @@
//! from one task to another.
//! - [mpsc](mpsc/index.html), a multi-producer, single-consumer channel for
//! sending values between tasks.
//! - [lock](lock/index.html), an asynchronous `Mutex`-like type.
//! - [`Mutex`](struct.Mutex.html), an asynchronous `Mutex`-like type.
//! - [watch](watch/index.html), a single-producer, multi-consumer channel that
//! only stores the **most recently** sent value.
pub use tokio_sync::{mpsc, oneshot, watch};
pub use tokio_sync::{Lock, LockGuard};
pub use tokio_sync::{Mutex, MutexGuard};