Multithreaded Workers & Concurrency
Execute CPU-intensive procedural level generation, pathfinding algorithms, and asset decoding in parallel background OS threads without dropping a single frame from your 60+ FPS game loop.
1. The Architecture of PyLua Workers
Unlike Python's Global Interpreter Lock (GIL) or Node.js single-threaded event loops, PyLua workers are true operating system threads (CreateThread on Windows, pthread_create on Linux/POSIX) with fully isolated Lua virtual machine states:
Main Process
┌──────────────────────────────────────┐
│ Main Thread (Game Loop @ 60 FPS) │ ──▶ Handles GLFW, OpenGL & Input
│ • Main VM State (lua_State* L_main) │
└──────────────────┬───────────────────┘
│
├── engine.createWorker("proc_gen.lua")
▼
┌──────────────────────────────────────┐
│ Worker Thread (Background Core) │ ──▶ Generates world chunk in background
│ • Isolated VM (lua_State* L_worker) │ 100% free of mutex lock contention!
└──────────────────────────────────────┘
2. Worker Functions Reference
| Function | Signature | Description |
|---|---|---|
engine.createWorker(scriptPath) |
(string) → Worker |
Spawns a background OS thread running the specified PyLua script in an isolated VM. |
engine.destroyWorker(worker) |
(Worker) → void |
Signals the worker thread to exit and frees its OS thread handle and VM memory. |
Procedural Generation Worker Example
main_game.lua
import engine
print("Launching terrain generator on background CPU core...")
terrainWorker = engine.createWorker("scripts/world_generator.lua")
-- Main game runs smoothly without freezing:
engine.run({
window = win,
update = function(dt) {
-- Frame updates remain locked at 60 FPS
}
})
-- Clean up worker when shutting down:
engine.destroyWorker(terrainWorker)