runtime.AddCleanup and C struct hierarchies: cleanup order?

94 views
Skip to first unread message

twp...@gmail.com

unread,
Feb 19, 2025, 4:11:50 PMFeb 19
to golang-nuts
The documentation for runtime.AddCleanup says:

> There is no specified order in which cleanups will run.

Given the following types:

type Parent struct {
    parentResource int
}

type Child struct {
    parent *Parent
    childResource int
}

and the following code:

parentResource := 0
parent := &Parent{
    parentResource: parentResource,
}
runtime.AddCleanup(parent, func (int) {}, parentResource)
childResource := 1
child := &Child{
    parent: parent,
    childResource: childResource
}
runtime.AddCleanup(child, func(int) {}, childResource)

is it guaranteed that the cleanup for childResource will run before the cleanup for parentResource?

Notes:
* I know that the structs here are small enough to be "tiny", but Child contains a pointer to Parent so the cleanups should run.
* The example here is for a specific case where the resources are allocated by a C library, the child resource is "owned" by the parent, and so it's important that the child resource cleanup runs before the parent resource cleanup.

Many thanks for any insight!

Ian Lance Taylor

unread,
Feb 19, 2025, 4:20:22 PMFeb 19
to twp...@gmail.com, golang-nuts
On Wed, Feb 19, 2025 at 1:12 PM twp...@gmail.com <twp...@gmail.com> wrote:
>
> The documentation for runtime.AddCleanup says:
>
> > There is no specified order in which cleanups will run.
>
> Given the following types:
>
> type Parent struct {
> parentResource int
> }
>
> type Child struct {
> parent *Parent
> childResource int
> }
>
> and the following code:
>
> parentResource := 0
> parent := &Parent{
> parentResource: parentResource,
> }
> runtime.AddCleanup(parent, func (int) {}, parentResource)
> childResource := 1
> child := &Child{
> parent: parent,
> childResource: childResource
> }
> runtime.AddCleanup(child, func(int) {}, childResource)
>
> is it guaranteed that the cleanup for childResource will run before the cleanup for parentResource?

No. There is no specified order in which cleanups will run.

The fact that child points to parent doesn't really matter here. They
can both be collected as garbage in the same GC pass, and that GC pass
may schedule both cleanups. There is no guarantee as to which cleanup
will be scheduler first or which will run first.

Ian

twp...@gmail.com

unread,
Feb 19, 2025, 4:25:22 PMFeb 19
to golang-nuts
Thank you for the super-fast and authoritative response!

OK, I will work on an alternative solution for cleaning up hierarchies in bottom-up order and will report back here if/when I find a good solution.

Regards,
Tom

Jason E. Aten

unread,
Feb 20, 2025, 5:58:47 AMFeb 20
to golang-nuts
Usually depth-first-search works just fine. 
Reply all
Reply to author
Forward
0 new messages