Getting access to the shared data

In this user handler, we need access to a database with users. Because the database is a Slab instance that's wrapped with a Mutex instance, we have to lock the mutex to have exclusive access to a slab. There's a Mutex::lock function that returns Result<MutexGuard, PoisonError<MutexGuard>>. MutexGuard is a scoped lock, which means it leaves the code block or scope in, and it implements the Deref and DerefMut traits to provide transparent access to data under the guard object.

It's a good practice to report all errors in the handler. You can log errors and return a 500 (Internal Error) HTTP code to the client. To keep it simple, we'll use an unwrap method and expect the mutex to lock correctly:

let mut users = user_db.lock().unwrap();

Here, we locked the Mutex for the duration of generating the request. In this case, where we're creating whole responses immediately, this is normal. In cases where the result is delayed or when we work with a stream, we shouldn't lock the mutex all time. This will create a bottleneck for all requests because the server can't process requests in parallel if all of them depend on a single shared object. For cases where you don't have results immediately, you can clone the reference to the mutex and lock it for the short time you need access to the data.

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

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