# Threading

> The rules of lanes - how many there are, how they meet, and what only one lane may do.

[Writing applications](https://kaigen3d.com/docs/writing-applications#every-core-runs-your-code) introduces lanes and the four ways to use them. This page is the rules that make them work.

## How many lanes

By default Kaigen runs one lane per fast physical core. You can change it, from the most to the least specific: `--lanes <n|auto>` on the command line, the `HZ_LANES` environment variable, or `HzAppConfig.lanes`. `--lanes 1` is a great way to check whether a bug is a threading bug.

On the web the automatic count is capped at 4.

## The one rule: same syncs on every lane

`lane_sync()` waits until every lane reaches it. So every lane has to make the same `lane_sync()` calls, the same number of times. A sync inside an `if` that only some lanes take hangs the app.

Hangs: the other lanes never get there:

```
if (is_main_thread()) {
  update_menu(state);
  lane_sync();
}
```

Works: do the work on one lane, sync on all:

```
if (is_main_thread()) {
  update_menu(state);
}
lane_sync();
```

In debug builds, the engine checks that every lane made the same syncs each frame, and tells you which lanes didn't and where.

`lane_sync()` is also when lanes see each other's writes. Something one lane wrote is only safe for the others to read after the next sync.

## Main lane or one lane

`is_main_thread()` means "lane 0", not "only once". Some things really have to be on lane 0: the window, the GPU commands and the UI. For those, use `is_main_thread()`.

Most work that should only run once doesn't care which lane runs it. For that, prefer an ECS system scheduled with `ecs_schedule_single`, which runs on whichever lane is free while the other lanes do other work. See [ECS](https://kaigen3d.com/docs/ecs).

## Splitting work

- `lane_range(count)` gives each lane its slice of `[0, count)`.
- `lane_kernel` and `lane_run` do the same with checked reads and writes (`hz/src/lib/lane_kernel.h`).
- `ConcurrentArray` collects results from every lane with an atomic append.
- `atomic_u32_*` and `atomic_u64_*` are there when you need them.

## Worth knowing

- Never put a `lane_sync()` inside an ECS system or a lane kernel. The scheduler does the syncing for you.
- Engine update functions (`ecs_flush`, `renderer_update`, the asset system) are made to be called by every lane. Calling them from one lane hangs.
- The ECS world outside of a schedule is main-lane state, so world setup in `app_init` usually starts with `if (!is_main_thread()) return;`.

The lane API is in `hz/src/lib/thread_context.h`.
