Re: [PATCH v4 5/5] rust: workqueue: add ScopedWork for non-'static work items
From: Gary Guo
Date: Wed Nov 25 2026 - 12:09:41 EST
On Wed Nov 25, 2026 at 4:44 PM GMT, Tejun Heo wrote:
> Hello, Alice.
>
> On Thu, Nov 19, 2026 at 02:12:46PM +0000, Alice Ryhl wrote:
>> Because the cancellation guarantee only holds if the destructor runs
>> before the bound Queue or any lifetime in T expires, ScopedWork::new()
>> (and thus new_scoped_work!) is unsafe and requires that the resulting
>> value is never forgotten and is dropped before 'wq or T's lifetimes end.
>
> I'm no Rust expert, so maybe this is me thinking too much in C, but
> requiring the compiler to understand and enforce that a workqueue outlives
> its scoped work items doesn't seem very convenient to use. Wouldn't it be
> easier to package e.g. a percpu refcnt with the workqueue, have each scoped
> work item hold a reference from creation to destruction, and make
> destroy_workqueue() keep draining until the count reaches zero?
The workqueue outliving scoped work is actually already enforced by the Rust
compiler, however Rust provides no guarantted destructor execution (say if you
construct the ScopedWork on a reference counted container and somehow leaked a
reference count).
Even in such cases, Rust lifetime will still make sure no external code will be
able to reference the leaked objects -- however, for work item a callback can
fire and access itself, hence we need this guarantee.
Adding a reference count to the workqueue solves the issue of work item
accessing the workqueue from its callback, however it is not sufficient, as the
workqueue may reference a device resource, and in such cases it captures a
lifetime of the device being bound. This lifetime cannot be reference counted as
when the device is unbound, the resources are gone and it's not permitted to use
reference counting to keep it alive.
So we still need the guaranteed destructor execution guarantee and reference
counting wq alone is not sufficient to remove this safety requirement.
Best,
Gary