From 2a8c540e38c3229e5414448b87327f6169a5b8c9 Mon Sep 17 00:00:00 2001 From: Marius S <39998+winding-lines@users.noreply.github.com> Date: Thu, 3 Sep 2026 06:02:20 -0700 Subject: [PATCH] origins.mojo on threads-mojo 0.3.0: the state by ref, the task by mut MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The typed parallel_for does in the library what this file did in user code: the origin of `totals` is bound to a ref argument, alive for the whole call, and the void * erasure happens once, out of sight. So Ctx, share and run go, and the program is the post's listing minus the pointer plumbing. Rewritten in place — the file has been linked to. Tests follow the API. The two Ctx-lifetime cases (returning one to a local, one outliving its block) have no equivalent now that there is no user-visible value carrying the origin, and are removed. share_* become state_*, the same diagnostic from parallel_for's ref argument. opaque_escapes_origin now uses the opaque overload directly: Int(…) on a tracked Pointer is where the origin stops. 6 passed, 0 failed. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_015or6oTZmb7EQTXTbALbBXY --- .github/workflows/ci.yml | 2 +- README.md | 35 ++++---- pixi.lock | 12 +-- pixi.toml | 2 +- src/origins.mojo | 89 +++++-------------- tests/caught/ctx_outlives_block.mojo | 13 --- tests/caught/return_ctx_to_local.mojo | 15 ---- tests/caught/share_immutable.mojo | 12 --- tests/caught/state_immutable.mojo | 14 +++ ...re_temporary.mojo => state_temporary.mojo} | 7 +- .../uncaught/field_deref_after_last_use.mojo | 17 ++-- tests/uncaught/opaque_escapes_origin.mojo | 23 +++-- tests/uncaught/plain_store_races.mojo | 21 +++-- 13 files changed, 97 insertions(+), 165 deletions(-) delete mode 100644 tests/caught/ctx_outlives_block.mojo delete mode 100644 tests/caught/return_ctx_to_local.mojo delete mode 100644 tests/caught/share_immutable.mojo create mode 100644 tests/caught/state_immutable.mojo rename tests/caught/{share_temporary.mojo => state_temporary.mojo} (57%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0880674..f865259 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,7 +32,7 @@ jobs: pixi run run-post | tee post.txt grep -q 'sum: 499500' post.txt - # Deliberate misuse: four cases the compiler must reject, four it must + # Deliberate misuse: two cases the compiler must reject, four it must # still accept (and get wrong in the documented way). - name: Caught and uncaught run: pixi run check diff --git a/README.md b/README.md index 377666f..7a7c161 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,14 @@ Two files, one program: - [`src/post.mojo`](src/post.mojo) — the post's whole program, plus the twenty-line `Ctx[T]` it relies on, exactly as published. - [`src/origins.mojo`](src/origins.mojo) — the same program with the origin - of `totals` kept in the context type instead of erased. `share(totals)` - captures it, `run[task](n, ctx)` holds it across the `parallel_for`, and the - compiler extends the lifetime of `totals` to cover the call. Sharing an - immutable argument, a temporary, or letting a `Ctx` outlive its state is a - compile error. The erasure to `void *` still happens — once, inside `run` — - because that is all a pthread can carry. + of `totals` kept instead of erased: `parallel_for[task](1000, totals)` + takes the state by `ref` and the task as `def(Int, mut Totals)`. An + argument is alive for the whole call, so the compiler extends the lifetime + of `totals` to cover the joins; a `read` argument or a temporary is a + compile error. The erasure to `void *` still happens — once, inside + threads.mojo — because that is all a pthread can carry. An earlier version + of this file did the same in user code with a `Ctx[T, origin]`, `share` and + `run`; threads-mojo 0.3.0 moved that into `parallel_for` itself. Both sum `0..1000` from every core through one shared atomic and print @@ -53,7 +55,7 @@ which wrote the `threads-mojo = { git = …, rev = … }` line in ## What the compiler catches, and what it does not -`pixi run check` builds eight deliberately wrong programs under +`pixi run check` builds six deliberately wrong programs under [`tests/`](tests/) and holds the compiler to a claim about each one. [`tests/caught/`](tests/caught/) must fail to compile, with the diagnostic the @@ -61,10 +63,8 @@ file names: | file | misuse | diagnostic | | --- | --- | --- | -| `share_immutable` | `share(x)` on a `read` argument | `cannot be converted from 'Totals' to ref 'Totals'` | -| `share_temporary` | `share(Totals(0))` | same | -| `return_ctx_to_local` | `return share(local)` | `cannot implicitly convert 'Ctx[Totals, origin_of(t)]' value to 'Ctx[Totals]'` | -| `ctx_outlives_block` | a `Ctx` assigned in a block, used after it | same | +| `state_immutable` | `parallel_for[task](n, x)` with `x` a `read` argument | `cannot be converted from 'Totals' to ref 'Totals'` | +| `state_temporary` | `parallel_for[task](n, Totals(0))` | same | [`tests/uncaught/`](tests/uncaught/) must compile with no diagnostic at all, and then print the wrong answer the file predicts: @@ -72,7 +72,7 @@ and then print the wrong answer the file predicts: | file | what goes wrong | output | | --- | --- | --- | | `untracked_ctx_drops_early` | the post's `Ctx` erases the origin; `totals` is destroyed at its last visible use, before any thread starts | `Totals dropped` printed first; sum `499499` (−1 + 499500, the tasks adding into the poisoned cell) | -| `opaque_escapes_origin` | `share(totals).opaque()` outside `run` — the boundary of what origins cover | same | +| `opaque_escapes_origin` | the opaque `parallel_for` on `opaque_ptr(Int(Pointer(to=totals)))` — `Int(…)` is where the origin stops, and the boundary of what the typed form covers | same | | `field_deref_after_last_use` | `totals.cell[]` copies the pointer field, which is the struct's last use, and the deref reads a destroyed object | `-1`; the method read `totals.sum()` gives `499500`, and so does the same field deref once the cell is an `OwnedPointer`, whose deref borrows the struct | | `plain_store_races` | a task writes `sum` with a plain load and store instead of the atomic — every task holds `mut` access to the same value and nothing says the type is safe to share | lost updates, every run; not a lifetime bug but the one an origin cannot express | @@ -83,11 +83,12 @@ those tests poisons the cell rather than freeing it, so the misuse stays a number that can be asserted instead of undefined behaviour. Three of the four are lifetime bugs, and each has a fix that exists today: -keep the origin in the type (`origins.mojo`), keep the erasure inside `run`, -and own heap memory through a type whose deref borrows the owner -(`OwnedPointer`, `List`) rather than a raw untracked `Pointer`. The fourth is -a different kind: `Ctx` gives a thousand tasks mutable access to one value, -and only an atomic in the task keeps that honest. Rust would refuse the +pass the state as a `ref` argument (the typed `parallel_for`), keep the +erasure inside the library, and own heap memory through a type whose deref +borrows the owner (`OwnedPointer`, `List`) rather than a raw untracked +`Pointer`. The fourth is a different kind: `parallel_for` gives a thousand +tasks `mut` access to one value, and only an atomic in the task keeps that +honest. Rust would refuse the aliased `&mut` and let the atomic through on the strength of `Sync`; Mojo has no such trait yet, so the race is invisible to the compiler and lands in the uncaught set with the others. diff --git a/pixi.lock b/pixi.lock index 3222ae7..730d3fb 100644 --- a/pixi.lock +++ b/pixi.lock @@ -69,7 +69,7 @@ environments: - conda: https://conda.modular.com/max-nightly/linux-64/mojo-compiler-1.0.0-release.conda - conda: https://conda.modular.com/max-nightly/noarch/mblack-26.5.0-release.conda - conda: https://conda.modular.com/max-nightly/noarch/mojo-python-1.0.0-release.conda - - conda_source: threads-mojo[031f6a35] @ git+https://github.com/magmalake/threads.mojo?rev=afa64b0e9ebf7f5dc2079f98b3d0e49dcd7bb6ab#afa64b0e9ebf7f5dc2079f98b3d0e49dcd7bb6ab + - conda_source: threads-mojo[1ee782b4] @ git+https://github.com/magmalake/threads.mojo?rev=1133606d6de0f48039e7ba2b427575b39b0d2010#1133606d6de0f48039e7ba2b427575b39b0d2010 osx-arm64: - conda: https://conda.anaconda.org/conda-forge/noarch/_python_abi3_support-1.0-hd8ed1ab_3.conda - conda: https://conda.anaconda.org/conda-forge/noarch/ca-certificates-2026.7.22-hbd8a1cb_0.conda @@ -116,7 +116,7 @@ environments: - conda: https://conda.modular.com/max-nightly/noarch/mojo-python-1.0.0-release.conda - conda: https://conda.modular.com/max-nightly/osx-arm64/mojo-1.0.0-release.conda - conda: https://conda.modular.com/max-nightly/osx-arm64/mojo-compiler-1.0.0-release.conda - - conda_source: threads-mojo[c57d0128] @ git+https://github.com/magmalake/threads.mojo?rev=afa64b0e9ebf7f5dc2079f98b3d0e49dcd7bb6ab#afa64b0e9ebf7f5dc2079f98b3d0e49dcd7bb6ab + - conda_source: threads-mojo[ab5a0344] @ git+https://github.com/magmalake/threads.mojo?rev=1133606d6de0f48039e7ba2b427575b39b0d2010#1133606d6de0f48039e7ba2b427575b39b0d2010 packages: - conda: https://conda.anaconda.org/conda-forge/linux-64/_openmp_mutex-4.5-20_gnu.conda build_number: 20 @@ -1100,8 +1100,8 @@ packages: run_exports: {} size: 61221085 timestamp: 1786294690001 -- conda_source: threads-mojo[031f6a35] @ git+https://github.com/magmalake/threads.mojo?rev=afa64b0e9ebf7f5dc2079f98b3d0e49dcd7bb6ab#afa64b0e9ebf7f5dc2079f98b3d0e49dcd7bb6ab - version: 0.2.2 +- conda_source: threads-mojo[1ee782b4] @ git+https://github.com/magmalake/threads.mojo?rev=1133606d6de0f48039e7ba2b427575b39b0d2010#1133606d6de0f48039e7ba2b427575b39b0d2010 + version: 0.3.0 build: hb0f4dca_0 subdir: linux-64 variants: @@ -1162,8 +1162,8 @@ packages: - conda: https://conda.anaconda.org/conda-forge/noarch/tzdata-2026c-h151e31d_0.conda - conda: https://conda.modular.com/max-nightly/linux-64/mojo-compiler-1.0.0-release.conda - conda: https://conda.modular.com/max-nightly/noarch/mojo-python-1.0.0-release.conda -- conda_source: threads-mojo[c57d0128] @ git+https://github.com/magmalake/threads.mojo?rev=afa64b0e9ebf7f5dc2079f98b3d0e49dcd7bb6ab#afa64b0e9ebf7f5dc2079f98b3d0e49dcd7bb6ab - version: 0.2.2 +- conda_source: threads-mojo[ab5a0344] @ git+https://github.com/magmalake/threads.mojo?rev=1133606d6de0f48039e7ba2b427575b39b0d2010#1133606d6de0f48039e7ba2b427575b39b0d2010 + version: 0.3.0 build: h60d57d3_0 subdir: osx-arm64 variants: diff --git a/pixi.toml b/pixi.toml index 4dc5bf9..ac8c79e 100644 --- a/pixi.toml +++ b/pixi.toml @@ -21,4 +21,4 @@ fmt = { cmd = "mojo format src tests" } mojo = "==1.0.0" # Added by `pixi shelf add threads-mojo`: the tin comes from GitHub as a pixi # source dependency, pinned at the revision mojoshelf published. -threads-mojo = { git = "https://github.com/magmalake/threads.mojo.git", rev = "afa64b0e9ebf7f5dc2079f98b3d0e49dcd7bb6ab" } +threads-mojo = { git = "https://github.com/magmalake/threads.mojo.git", rev = "1133606d6de0f48039e7ba2b427575b39b0d2010" } diff --git a/src/origins.mojo b/src/origins.mojo index de6af36..8cb8d13 100644 --- a/src/origins.mojo +++ b/src/origins.mojo @@ -9,69 +9,22 @@ is through an untracked pointer the compiler cannot see, the last visible use is `Ctx[Totals].to(totals)` — before `parallel_for` runs. With a `Totals` that owns heap memory, a thousand tasks then write into a freed block. -Here the context carries the origin of the state it points to. `share` -captures it, `run` holds a value of that type across the `parallel_for`, and -the compiler extends the lifetime of `totals` to cover the call — no later use -of `totals` required. What the compiler will now reject: sharing an immutable -argument or a temporary, returning a `Ctx` to a local, and letting a `Ctx` -outlive its block. - -The origin stops at `opaque()`. A pthread carries one `void *`, so the task -side gets it back through `Ctx[Totals].of(ptr)` with the untracked default — -inside a task the origin is genuinely unknowable. Keep `opaque()` as the one -place the erasure happens, inside `run`, and nothing else in the program needs -to reason about it. +Here `totals` goes to `parallel_for` as a `ref` argument and reaches every +task as `mut`. An argument is alive for the whole call, joins included, so +the compiler extends the lifetime of `totals` to cover it with no later use +required; and a `ref` demands a mutable binding, so a `read` argument or a +temporary is rejected where the call is made. The erasure to `void *` still +happens — a pthread carries one pointer — but once, inside the library, and +nothing in this file handles it. + +An earlier version of this file did the same job in user code: a +`Ctx[T, origin]` built by `share(totals)` and held across the call by +`run[task](n, ctx)`. threads-mojo 0.3.0 moved that into `parallel_for` +itself, which is why the program below is the post's listing minus the +pointer plumbing. """ -from threads import AtomicCounter, OpaquePtr, WorkFn, num_cpus, parallel_for - - -@fieldwise_init -struct Ctx[T: AnyType, origin: MutOrigin = MutUntrackedOrigin]( - Copyable, Movable -): - """A typed view of the pointer each task is handed, with an origin. - - On the calling side the origin is the state's own — `share` builds one. - Inside a task it defaults to `MutUntrackedOrigin`, because the pointer - arrived through `void *` and there is nothing to track it against. - """ - - var _ptr: Pointer[Self.T, Self.origin] - - @staticmethod - def of(ptr: OpaquePtr) -> Self: - """The task-side view: reinterpret the opaque pointer as a `T`.""" - return Self(Pointer[Self.T, Self.origin](unsafe_from_address=Int(ptr))) - - def __getitem__(self) -> ref[Self.origin] Self.T: - return self._ptr[] - - def opaque(self) -> OpaquePtr: - """Erase the origin. The one operation the compiler cannot check.""" - return OpaquePtr(unsafe_from_address=Int(self._ptr)) - - -def share[ - T: AnyType, origin: MutOrigin -](ref[origin] state: T) -> Ctx[T, origin]: - """A `Ctx` whose origin is `state`'s own — `origin_of(state)`. - - Requires a mutable binding: an immutable argument or a temporary is - rejected at the call site. - """ - return Ctx[T, origin](Pointer(to=state)) - - -def run[ - T: AnyType, origin: MutOrigin, //, work: WorkFn -](n_tasks: Int, ctx: Ctx[T, origin], num_workers: Int = 0) raises: - """`parallel_for`, taking the tracked context rather than the pointer. - - `ctx` is alive for the whole call, so the state it points to is too. The - erasure to `void *` happens here and nowhere else. - """ - parallel_for[work](n_tasks, ctx.opaque(), num_workers) +from threads import AtomicCounter, num_cpus, parallel_for @fieldwise_init @@ -84,13 +37,17 @@ def counter(ref cell: Int64) -> AtomicCounter: return AtomicCounter.at(Int(Pointer(to=cell))) -def task(i: Int, ptr: OpaquePtr) -> None: - """The work function: a top-level `def`, since a thread body is thin.""" - var t = Ctx[Totals].of(ptr) - _ = counter(t[].sum).fetch_add(Int64(i)) +def task(i: Int, mut totals: Totals) -> None: + """The work function: a top-level `def`, since a thread body is thin. + + Every task gets `mut` access to the same `Totals` at the same time; the + atomic is what makes that honest. A plain `totals.sum += i` would compile + just as well — see `tests/uncaught/plain_store_races.mojo`. + """ + _ = counter(totals.sum).fetch_add(Int64(i)) def main() raises: var totals = Totals(0) - run[task](1000, share(totals)) + parallel_for[task](1000, totals) print("cores:", num_cpus(), " sum:", totals.sum) diff --git a/tests/caught/ctx_outlives_block.mojo b/tests/caught/ctx_outlives_block.mojo deleted file mode 100644 index 1cd8490..0000000 --- a/tests/caught/ctx_outlives_block.mojo +++ /dev/null @@ -1,13 +0,0 @@ -# Same refusal, one scope down: `t` dies with the block, `c` does not. -# expect-error: cannot implicitly convert 'Ctx[Totals, origin_of(t)]' value to 'Ctx[Totals]' -from origins import Ctx, Totals, run, share, task - - -def main() raises: - var c: Ctx[Totals] - var n = 1 - if n == 1: - var t = Totals(0) - c = share(t) - run[task](1000, c) - print(c[].sum) diff --git a/tests/caught/return_ctx_to_local.mojo b/tests/caught/return_ctx_to_local.mojo deleted file mode 100644 index 5879041..0000000 --- a/tests/caught/return_ctx_to_local.mojo +++ /dev/null @@ -1,15 +0,0 @@ -# `share(t)` has type `Ctx[Totals, origin_of(t)]`, and the compiler will not -# quietly widen that to the untracked origin on the way out of the function. -# expect-error: cannot implicitly convert 'Ctx[Totals, origin_of(t)]' value to 'Ctx[Totals]' -from origins import Ctx, Totals, run, share, task - - -def make() -> Ctx[Totals]: - var t = Totals(0) - return share(t) - - -def main() raises: - var c = make() - run[task](1000, c) - print(c[].sum) diff --git a/tests/caught/share_immutable.mojo b/tests/caught/share_immutable.mojo deleted file mode 100644 index 5e02fae..0000000 --- a/tests/caught/share_immutable.mojo +++ /dev/null @@ -1,12 +0,0 @@ -# A `read` argument has an immutable origin; `share` demands a mutable one. -# expect-error: cannot be converted from 'Totals' to ref 'Totals' -from origins import Totals, run, share, task - - -def sum_of(totals: Totals) raises -> Int64: - run[task](1000, share(totals)) - return totals.sum - - -def main() raises: - print(sum_of(Totals(0))) diff --git a/tests/caught/state_immutable.mojo b/tests/caught/state_immutable.mojo new file mode 100644 index 0000000..5f156ae --- /dev/null +++ b/tests/caught/state_immutable.mojo @@ -0,0 +1,14 @@ +# A `read` argument has an immutable origin; `parallel_for` takes the state +# by mutable `ref`, so the call is refused where it is made. +# expect-error: cannot be converted from 'Totals' to ref 'Totals' +from origins import Totals, task +from threads import parallel_for + + +def sum_of(totals: Totals) raises -> Int64: + parallel_for[task](1000, totals) + return totals.sum + + +def main() raises: + print(sum_of(Totals(0))) diff --git a/tests/caught/share_temporary.mojo b/tests/caught/state_temporary.mojo similarity index 57% rename from tests/caught/share_temporary.mojo rename to tests/caught/state_temporary.mojo index b0872e8..8e7db45 100644 --- a/tests/caught/share_temporary.mojo +++ b/tests/caught/state_temporary.mojo @@ -1,9 +1,8 @@ # A temporary dies at the end of the statement; there is nothing to share. # expect-error: cannot be converted from 'Totals' to ref 'Totals' -from origins import Ctx, Totals, run, share, task +from origins import Totals, task +from threads import parallel_for def main() raises: - var c = share(Totals(0)) - run[task](1000, c) - print(c[].sum) + parallel_for[task](1000, Totals(0)) diff --git a/tests/uncaught/field_deref_after_last_use.mojo b/tests/uncaught/field_deref_after_last_use.mojo index 6aa2f3a..af84f02 100644 --- a/tests/uncaught/field_deref_after_last_use.mojo +++ b/tests/uncaught/field_deref_after_last_use.mojo @@ -14,8 +14,7 @@ # expect: Owned dropped from std.memory import OwnedPointer from std.memory.alloc import unsafe_alloc -from origins import Ctx, run, share -from threads import AtomicCounter, OpaquePtr +from threads import AtomicCounter, parallel_for struct Totals(Movable): @@ -56,22 +55,20 @@ struct Owned(Movable): print("Owned dropped") -def task(i: Int, ptr: OpaquePtr) -> None: - var t = Ctx[Totals].of(ptr) - _ = AtomicCounter.at(Int(t[].cell)).fetch_add(Int64(i)) +def task(i: Int, mut t: Totals) -> None: + _ = AtomicCounter.at(Int(t.cell)).fetch_add(Int64(i)) -def owned_task(i: Int, ptr: OpaquePtr) -> None: - var t = Ctx[Owned].of(ptr) - _ = AtomicCounter.at(Int(Pointer(to=t[].cell[]))).fetch_add(Int64(i)) +def owned_task(i: Int, mut o: Owned) -> None: + _ = AtomicCounter.at(Int(Pointer(to=o.cell[]))).fetch_add(Int64(i)) def main() raises: var totals = Totals() - run[task](1000, share(totals)) + parallel_for[task](1000, totals) print("via method:", totals.sum()) print("via field deref:", totals.cell[]) var owned = Owned() - run[owned_task](1000, share(owned)) + parallel_for[owned_task](1000, owned) print("via OwnedPointer field deref:", owned.cell[]) diff --git a/tests/uncaught/opaque_escapes_origin.mojo b/tests/uncaught/opaque_escapes_origin.mojo index 7533002..effa328 100644 --- a/tests/uncaught/opaque_escapes_origin.mojo +++ b/tests/uncaught/opaque_escapes_origin.mojo @@ -1,12 +1,14 @@ -# The tracked `Ctx` fixes the drop — until `opaque()` is called outside `run`. -# The `void *` carries no origin, the temporary `Ctx` dies with the statement, -# and `totals` goes with it. This is the boundary of what origins can cover. +# The typed `parallel_for` fixes the drop — the opaque one does not. `Int(…)` +# turns a pointer whose origin is `totals`'s own into a number, the number +# into an untracked `OpaquePtr`, and from there the compiler sees no use of +# `totals`, so it is destroyed on the spot. This is the boundary of what +# origins can cover: the opaque form is the right tool for a hand-laid-out +# block of cells, and the wrong one for a local you stop mentioning. # expect: Totals dropped # expect: before parallel_for # expect: after parallel_for: 499499 from std.memory.alloc import unsafe_alloc -from origins import Ctx, share -from threads import AtomicCounter, OpaquePtr, parallel_for +from threads import AtomicCounter, OpaquePtr, opaque_ptr, parallel_for struct Totals(Movable): @@ -28,15 +30,18 @@ struct Totals(Movable): self.cell[] = -1 +def at(ptr: OpaquePtr) -> ref[MutUntrackedOrigin] Totals: + return Pointer[Totals, MutUntrackedOrigin](unsafe_from_address=Int(ptr))[] + + def task(i: Int, ptr: OpaquePtr) -> None: - var t = Ctx[Totals].of(ptr) - _ = AtomicCounter.at(Int(t[].cell)).fetch_add(Int64(i)) + _ = AtomicCounter.at(Int(at(ptr).cell)).fetch_add(Int64(i)) def main() raises: var totals = Totals() - var ptr = share(totals).opaque() + var ptr = opaque_ptr(Int(Pointer(to=totals))) print("before parallel_for") parallel_for[task](1000, ptr) # Not `totals.cell` — a use of `totals` here would move the drop past it. - print("after parallel_for:", Ctx[Totals].of(ptr)[].cell[]) + print("after parallel_for:", at(ptr).cell[]) diff --git a/tests/uncaught/plain_store_races.mojo b/tests/uncaught/plain_store_races.mojo index 68e6441..7a6f8db 100644 --- a/tests/uncaught/plain_store_races.mojo +++ b/tests/uncaught/plain_store_races.mojo @@ -1,18 +1,18 @@ -# Not a lifetime bug: a data race. `Ctx.__getitem__` hands every task a -# mutable ref to the same `Totals`, and nothing stops a task writing to -# `sum` with a plain load and store instead of the atomic. Rust rejects this +# Not a lifetime bug: a data race. `parallel_for` hands every task `mut` +# access to the same `Totals`, and nothing stops a task writing to `sum` +# with a plain load and store instead of the atomic. Rust rejects this # before threads come into it — `&mut` aliased across closures is an # exclusivity error, and the atomic works through `&AtomicI64` because that # type is `Sync`. Mojo has no interior-mutability marker, so there is no way -# for `share` to demand one; the origin says only how long `totals` lives. +# for `parallel_for` to demand one; the origin says only how long `totals` +# lives. # # The window between load and store is widened on purpose so that the lost # updates are a certainty rather than a likelihood, and the worker count is # fixed so a single-core runner cannot serialise the tasks by accident. # expect: plain store, lost updates: True from std.time import perf_counter_ns -from origins import Ctx, run, share -from threads import OpaquePtr +from threads import parallel_for @fieldwise_init @@ -20,16 +20,15 @@ struct Totals(Copyable, Movable): var sum: Int64 -def task(i: Int, ptr: OpaquePtr) -> None: - var t = Ctx[Totals].of(ptr) - var seen = t[].sum +def task(i: Int, mut t: Totals) -> None: + var seen = t.sum var t0 = perf_counter_ns() while perf_counter_ns() - t0 < 20_000: pass - t[].sum = seen + Int64(i) + t.sum = seen + Int64(i) def main() raises: var totals = Totals(0) - run[task](1000, share(totals), num_workers=4) + parallel_for[task](1000, totals, num_workers=4) print("plain store, lost updates:", totals.sum != 499500)