Files
ecs/ecs/sharing.sakura
T
2026-10-30 06:25:53 -05:00

58 lines
2.3 KiB
Plaintext

#! Contains sharing a world between threads: several passing over it at once,
#! each over what no other writes, as an engine runs systems reaching
#! different components on threads of its own.
module ecs;
#! Lets several threads pass over the world at once, until `end_sharing`, as an
#! engine runs systems reaching different components on threads of its own.
#! Each thread passes over it by `each`, queries, and chunks, gets and replaces
#! the components entities have, and reads its resources. What would move an
#! entity, a component given that it lacks or taken, or a despawn, is deferred,
#! as within a pass, and made as the sharing ends, in the order the threads
#! deferred them.
#!
#! Threads may read a component at once, but one writing it must be the only
#! thread reaching it, which the world leaves to its caller, as an engine knows
#! what each system reads and writes. While shared, the world can't spawn
#! entities, meet types it hasn't, be given resources or have them taken, or
#! `apply` commands; `par_each` calls its function on its own thread, as the
#! threads sharing the world are its threads.
#! @remarks Only the thread that began sharing ends it, once the others are
#! done with the world.
pub def world::begin_sharing(&mut this): void {
if this.sharing {
fault("`begin_sharing` was called on a world threads share already.");
}
if this.parallel || this.deferring > 0 {
fault("`begin_sharing` can't run while a pass goes over the world: run it after.");
}
this.sharing = true;
this.deferring++;
}
#! Ends the sharing `begin_sharing` began, once every other thread is done with
#! the world, and makes what the threads deferred.
pub def world::end_sharing(&mut this): void {
if !this.sharing {
fault("`end_sharing` was called on a world no threads share.");
}
this.sharing = false;
this.deferring--;
if this.pending.length > 0 {
this.flush();
}
}
#! Whether threads share the world, between `begin_sharing` and `end_sharing`.
pub val world::shared: bool {
get => this.sharing;
}
# Stops the program where threads share the world, which can't do what's named.
def world::refuse_while_shared(&this, what: strview): void {
if this.sharing {
fault($"A world threads share can't {what}: do it before `begin_sharing`, or after `end_sharing`.");
}
}