Threading

Writing applications 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.

Splitting work

Worth knowing

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