Musa-Cpp-Lib-V2/lib/Base/Base_Thread_Context.cpp
2025-11-23 04:09:52 -05:00

101 lines
2.4 KiB
C++

// See Context_Base in jai, and TCTX in raddebugger:
struct Thread_Context {
Arena* temp; // Used for temporary allocations, scratch space.
Arena* arena; // general purpose local arena
Allocator allocator;
s32 thread_idx;
u16 _padding0;
u16 GPAllocator_alignment = 16;
// Logger logger;
// Stack_Trace* stack_trace;
// #TODO: other debug information
// #TODO:
// Array<Thread*> threads_created; // maybe should be linked-list?
// Thread* thread_that_created_me = nullptr; // so we can remove from above array
// Mutex thread_context_mutex;
string thread_name;
};
Thread_Context* get_thread_context();
struct Push_Arena {
Thread_Context* context;
Allocator original_allocator;
Push_Arena(Arena* arena) {
Assert(is_valid(arena));
context = get_thread_context();
Assert(context != nullptr);
original_allocator = context->allocator;
context->allocator = get_allocator(arena);
}
~Push_Arena() {
context->allocator = original_allocator;
}
};
struct Push_Allocator {
Thread_Context* context;
Allocator old_allocator;
Push_Allocator (Allocator new_allocator) {
context = get_thread_context();
old_allocator = context->allocator;
context->allocator = new_allocator;
}
~Push_Allocator () {
context->allocator = old_allocator;
}
};
// Thread-local allocators:
PROTOTYPING_API Allocator get_temp_allocator();
PROTOTYPING_API Allocator get_context_allocator();
// C_LINKAGE thread_static TCTX* tctx_thread_local;
thread_static Thread_Context* thread_local_context;
// Start from w32_entry_point_caller ->
// see main_thread_base_entry_point
// //- rjf: set up thread context
// TCTX *tctx = tctx_alloc();
// tctx_select(tctx);
// See: tctx_alloc(void)
// Let's do arenas first.
void init_thread_context(Thread_Context* tctx) {
// Should be Arena-bootstrapped with Temp Arena maybe?
// #TODO - call from entry point.
}
Thread_Context* get_thread_context() {
return (Thread_Context*)thread_local_context;
}
force_inline Allocator get_temp_allocator() {
return get_allocator(get_thread_context()->temp);
}
force_inline Allocator get_context_allocator() {
Thread_Context* context = get_thread_context();
return context->allocator;
}
void temp_reset_keeping_memory() {
Thread_Context* context = get_thread_context();
arena_reset_keeping_memory(context->temp);
}
void temp_reset() {
Thread_Context* context = get_thread_context();
arena_reset(context->temp);
}