107 lines
2.2 KiB
Markdown
107 lines
2.2 KiB
Markdown
# Worker Pool
|
|
|
|
### Pool
|
|
|
|
```go
|
|
type Pool struct { ... }
|
|
|
|
// Create a pool with specified number of workers
|
|
func NewPool(numWorkers int) (*Pool, error)
|
|
|
|
// Submit a job with default context
|
|
func (p *Pool) Submit(bytecode []byte, ctx *Context) (any, error)
|
|
|
|
// Submit with timeout/cancellation support
|
|
func (p *Pool) SubmitWithContext(ctx context.Context, bytecode []byte, execCtx *Context) (any, error)
|
|
|
|
// Shutdown the pool
|
|
func (p *Pool) Shutdown() error
|
|
|
|
// Get number of active workers
|
|
func (p *Pool) ActiveWorkers() uint32
|
|
```
|
|
|
|
### Context
|
|
|
|
```go
|
|
type Context struct { ... }
|
|
|
|
// Create a new execution context
|
|
func NewContext() *Context
|
|
|
|
// Set a value
|
|
func (c *Context) Set(key string, value any)
|
|
|
|
// Get a value
|
|
func (c *Context) Get(key string) any
|
|
```
|
|
|
|
## Basic Usage
|
|
|
|
```go
|
|
// Create worker pool
|
|
pool, err := workers.NewPool(4)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer pool.Shutdown()
|
|
|
|
// Compile bytecode (typically done once and reused)
|
|
state := luajit.New()
|
|
bytecode, err := state.CompileBytecode(`
|
|
return ctx.message .. " from Lua"
|
|
`, "script")
|
|
state.Close()
|
|
|
|
// Set up execution context
|
|
ctx := workers.NewContext()
|
|
ctx.Set("message", "Hello")
|
|
ctx.Set("params", map[string]any{"id": "123"})
|
|
|
|
// Execute bytecode
|
|
result, err := pool.Submit(bytecode, ctx)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
fmt.Println(result) // "Hello from Lua"
|
|
```
|
|
|
|
## With Timeout
|
|
|
|
```go
|
|
// Create context with timeout
|
|
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
|
defer cancel()
|
|
|
|
// Execute with timeout
|
|
result, err := pool.SubmitWithContext(ctx, bytecode, execCtx)
|
|
if err != nil {
|
|
// Handle timeout or error
|
|
}
|
|
```
|
|
|
|
## In Lua Scripts
|
|
|
|
Inside Lua, the context is available as the global `ctx` table:
|
|
|
|
```lua
|
|
-- Access a simple value
|
|
local msg = ctx.message
|
|
|
|
-- Access nested values
|
|
local id = ctx.params.id
|
|
|
|
-- Return a result to Go
|
|
return {
|
|
status = "success",
|
|
data = msg
|
|
}
|
|
```
|
|
|
|
## Important Notes
|
|
|
|
- The pool is thread-safe; multiple goroutines can submit jobs concurrently
|
|
- Each execution is isolated; global state is reset between executions
|
|
- Bytecode should be compiled once and reused for better performance
|
|
- Context values should be serializable to Lua (numbers, strings, booleans, maps, slices) |