Fix ambiguous explanation of MutexGuard unlocking in ch20-02

Fixes https://github.com/rust-lang/book/issues/1871, reference: https://doc.rust-lang.org/reference/destructors.html#destructors
This commit is contained in:
Yichao 'Peak' Ji
2019-10-03 16:29:34 +08:00
committed by GitHub
parent 04806c80be
commit d19da84cae

View File

@@ -1173,15 +1173,15 @@ method returns. At compile time, the borrow checker can then enforce the rule
that a resource guarded by a `Mutex` cannot be accessed unless we hold the
lock. But this implementation can also result in the lock being held longer
than intended if we dont think carefully about the lifetime of the
`MutexGuard<T>`. Because the values in the `while` expression remain in scope
for the duration of the block, the lock remains held for the duration of the
call to `job.call_box()`, meaning other workers cannot receive jobs.
`MutexGuard<T>`. Because the values in the `while let` expression remain in
scope for the duration of the block, the lock remains held for the duration of
the call to `job.call_box()`, meaning other workers cannot receive jobs.
By using `loop` instead and acquiring the lock and a job within the block
rather than outside it, the `MutexGuard` returned from the `lock` method is
dropped as soon as the `let job` statement ends. This ensures that the lock is
held during the call to `recv`, but it is released before the call to
`job.call_box()`, allowing multiple requests to be serviced concurrently.
By using `loop` instead and acquiring the lock without assigning to a variable,
the temporary `MutexGuard` returned from the `lock` method is dropped as soon as
the `let job` statement ends. This ensures that the lock is held during the call
to `recv`, but it is released before the call to `job.call_box()`, allowing
multiple requests to be serviced concurrently.
[creating-type-synonyms-with-type-aliases]:
ch19-04-advanced-types.html#creating-type-synonyms-with-type-aliases