State sharing without blocking

In the first optimization, we will replace Mutex with RwLock, because Mutex is locked for both reading and writing, but RwLock allows us to have a single writer or multiple readers. It allows you to avoid blocking for reading the value if no one updates the value. This applies to our example, as we rarely update a shared value, but have to read it from multiple instances of handlers.

RwLock is an alternative to Mutex that separates readers and writers, but the usage of RwLock is as simple as Mutex. Replace Mutex to RwLock in the State struct:

#[derive(Clone)]
struct State {
// last_minute: Arc<Mutex<String>>,
last_minute: Arc<RwLock<String>>,
}

Also, we have to replace a creation of the last_minute reference counter to the corresponding type:

// let last_minute = Arc::new(Mutex::new(value));
let last_minute = Arc::new(RwLock::new(value));

In the code of the worker, we will use the write method of RwLock to lock the value for writing to set a new time value. Its exclusive lock will block all potential readers and writers with a single writer that can change the value:

// let mut last_minute = last_minute_ref.lock().unwrap();
let mut last_minute = last_minute_ref.write().unwrap();

Since the worker will take an exclusive lock once per three seconds, it's a small price to pay to increase the amount of simultaneous readers.

In the handler, we will use the read method to lock RwLock for reading:

// let last_minute = req.state().last_minute.lock().unwrap();
let last_minute = req.state().last_minute.read().unwrap();

This code won't be blocked by other handlers, excluding the case when a worker updates a value. It allows all handlers to work simultaneously.

Now we can implement the second improvement—avoid cloning of values and using them by references.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.255.187