# Threads, processes and background blocks
Which thread dies when, `process`, `std::async` / `std::after` / `std::every` / `std::cancel`, generation tokens, error isolation (a server error stops the rest of its line). Open for loops, timers, rounds, anything long-running.

## Processes and threads
```js
function give_kit(amount) { player::give_item(item("bread"), amount) }
process spawn_wave() { ... }       // runs in parallel
give_kit(3)
```
Threads die with their target: code in a player event, and a process started from it with `name()`
(target = current player), stops MID-EXECUTION when the player leaves / the entity dies. A world-wide loop
goes in top-level code (world_start) or `code::start_process("spawn_wave", target_mode = "NO_TARGET")`.
A `repeat::forever()` in `player_join` is a per-player loop that ends when that player quits. BUT `/play` typed
again while the world is already in play mode fires `player_join` again and the OLD loop keeps running (two loops →
double coins/ticks; `world_start` does not re-fire; `/build` and a deploy stop all loops — verified, server-check-13).
## Background blocks: std::async, std::after, std::every
Background blocks — write these instead of hand-made processes (each is exactly the process you would write):
```js
std::async { risky_nbt_stuff() }                   // own process: an error inside does not stop THIS line (verified)
std::async(target = "NO_TARGET") { boss_loop() }   // outlives the player's quit
std::after(40) { door_open = 0 }                   // in 40 ticks (2 s); the code below goes on at once
std::every(1s) { hud() }                           // every 20 ticks, first run at once; does not block the line
std::every(20, "hud") { hud() }   ...   std::cancel("hud")   // a key: stop it from anywhere in the module
```
- Time is in ticks: 20 = 1 s, or `1s` / `5s` / `20t`. A variable or expression is computed at the start.
- Cost: a process `jmcc.pN` + `code::start_process` ≈4, ≈8 if the body reads your `var`s (they arrive as a copy);
  each `line var` it reads is copied for you (+1). The process runs at once, in the same tick, up to its first wait.
- Writing a captured variable inside changes only the block's copy (warning `async-write`): shared state → `game var`.
- `std::every` replaces itself: running the same `every` again (a second `/play` → `player_join`) stops the old loop
  at its next step — no generation token needed (verified). One counter per player (per entity); in world code one per world.
  A step costs ≈1 extra (one `>`). Stop from inside: `break`; from outside: a key + `std::cancel("key")`.
  `continue` in its body is an error — wrap the rest of the step in `if`.
- `std::after(t, "key")`: starting it again with the same key cancels the pending one; `std::cancel("key")` too.
- `return` ends the block; `break` / `continue` cannot reach a loop outside it (error). A `try` around the block does
  not catch errors inside (other line, warning `try-async`) — put `try` inside.
- `target = "NO_TARGET"` (`std::async`, `std::after` without a key): no player there — `%player%` stays text and
  `player::` without `<selector>` reaches nobody (warning). Pass the name: `line var p = "%player%"` outside,
  `select::player_by_name([p])` inside.
- Not inside `std::session` for `std::every` (the session would never end; warning). A block is not a value
  (`var x = std::async { }` is an error).
## Generation token by hand
By hand (also works) — guard a per-player loop with a generation token (verified):
```
game var %player%_loop
event<player_join> {
  %player%_loop = value::timestamp
  line var my = %player%_loop
  repeat::forever() {
    code::wait(1, time_unit = "SECONDS")
    if (%player%_loop != my) { code::stop_repeat() }   // a newer join took over
    // ... per-player work
  }
}
```
A NO_TARGET loop outlives whatever it manages (a boss, a round): give it a generation token, see topic recipes «Boss fight».

## Error isolation
Error isolation: a server error (wrong type, bad or guessed argument) stops the REST OF ITS CODE LINE — the
actions after it, a `repeat::forever` later in that line, and everything in the functions the line calls (an
error inside a called function stops the caller's line too). Other events and processes go on. (Verified: an
error stops its line; an error inside a called function stops the caller's line too (server-check-8); `break` in
a called function ends the caller's line. A started process is its own line: an error there does not stop the line that started it — verified.) So:
- top-level code is ONE line (world_start): start a long-running world loop FIRST there, or put it in its own
  line with `std::every(20) { ... }` / `std::async(target = "NO_TARGET") { ... }`; before a loop keep only plain variable setup;
- keep risky or unverified actions (item components, NBT, ray traces, guessed enum values) out of the loop's
  line: run them in `std::async { ... }` (their own process), so an error ends only that run.

## Selecting a player: std::with_player
`std::with_player(name) { ... }` = `select::player_by_name([name])`, the block, `select::reset()` — the reset also
goes before every `return` / `break` / `continue` that leaves the block. Inside, read values with `<current>`
(`value::health<current>`): a bare `value::x` there is an error — whether it reads the selection in a player event
is not checked yet.

## Verified (also in topic server-facts)
- Background blocks (sc-lang57): `std::every` in `player_join` + a second `/play` — the old loop stops, only the new
  one runs; the counter is per player (top-level code: one per world); `break` works also when a long body is cut
  into `jmcc.fN`; a server error inside `std::async` does not stop the caller; the caller's `var`s arrive as copies.
- The `entity_death` thread keeps running after `code::wait` (the entity is already dead, the code goes on) —
  the exception to "threads die with their target".
