Locking
Locking
Posted Sep 23, 2024 19:51 UTC (Mon) by NYKevin (subscriber, #129325)In reply to: Locking by atnot
Parent article: Resources for learning Rust for kernel development
You can steal the API from std::thread::scope(), but I'm not sure how applicable that is in all cases. The basic idea is as follows:
* The caller passes in a closure, which takes some opaque scope object by reference.
* The scope object provides methods for the closure to do whatever thing(s) the caller wants to do (in the case of thread::scope(), spawn threads).
* The scope object internally keeps track of whatever thing(s) the closure does, and whatever cleanup operation(s) may be required in response (in the case of thread::scope(), join those threads to ensure they do not outlive the scope).
* Because the closure is called from the callee, the callee always gets control back after the closure returns (or panics, if unwinding is enabled and we use catch_unwind). The callee can ensure that all cleanup code is executed, by referencing the scope object's internal data. Since the closure does not receive ownership of the scope object, it cannot forget it.
* In the case of thread::scope(), the scope object also gives the closure "handles" which it can use to reference the operations (threads) it has performed (spawned). But if the closure forgets these handles, it has no effect on the scope object, because they're just handles - they do not need to be dropped for the scope object to do the appropriate cleanup.
* Lifetime parameters are used to prohibit the closure from smuggling these objects and references out to the caller and trying to carry out further mischief with them.
This is obviously not as flexible as true linear types would be, but it is better than nothing.
