The following Actix Web code snippet attempts to create a shared counter, but it has a subtle performance bug. Identify the problem.

Go & Rust interview question for Advanced practice.

Answer

Using std::sync::Mutex in an async handler is inefficient because .lock() is a blocking call that will block the worker thread.

Explanation

Option B is correct. While the code is logically correct and will not deadlock in this simple case, it's a performance bug. std::sync::Mutex::lock is a blocking function. When called in an async context, it blocks the entire worker thread, preventing it from handling any other concurrent requests. This negates the benefits of using an async framework. The correct solution is to use an async-aware mutex, such as tokio::sync::Mutex, and await the lock: let mut num = counter.lock().await;.

Related Questions