Skip to content

Closures made in a loop capture a Copy local by place: every closure sees the last iteration's value (spec §12.4: Copy capture copies) #1471

Closed

Description

@ehartford

Found while writing the #1374 concurrency fixture (threads spawned in a loop all ran with the last index).

Spec §12.4 Capture Semantics: "For Copy values, default capture copies the value." A closure created inside a loop body captures the loop's Copy local (the for binding, or a fresh let in the body) by place instead, so every closure created by the loop observes the value of the final iteration.

Repro (installed compiler v0.15.2.1 and a stage1 of origin/main ba2d5d1):

fn main:
    var fs: Vec[fn() -> i32] = Vec.new()
    for i in 0..3:
        let n = i
        fs.push(() => n * 10)
    var gs: Vec[fn() -> i32] = Vec.new()
    var j = 0
    while j < 3:
        let m = j
        gs.push(() => m * 10)
        j = j + 1
    for k in 0..3:
        print(f"{k}: {fs[k]()} {gs[k]()}")

Expected:

0: 0 0
1: 10 10
2: 20 20

Actual:

0: 20 20
1: 20 20
2: 20 20

Capturing the for binding directly (fs.push(() => i * 10)) gives the same 20 20 20. A closure returned from a function (fn mk(x: i32) -> fn() -> i32: () => x * 10) keeps its own value, so the defect is specific to closures created repeatedly at one site in one frame: the capture environment (or the captured slot) is shared across iterations.

With threads this is also a data race: for i in 0..8: handles.push(spawn_os(() => run_once(i))) ran run_once(7) in several threads (#974 is the missing ScopedSend check for spawn_os; this is the capture itself).

Workaround used: test/behavior/behav_run_concurrent_same_program.w (#1374) spells one closure site per thread (spawn_os(() => run_once(0)) … run_once(7)); the fix can fold them back into a loop.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions