Skip to content

Is *vm.Program thread-safe? Can multiple threads access this for expr.Run(..)? #707

Answered by antonmedv
rchougule asked this question in Q&A
Discussion options

You must be logged in to vote

Expr supports concurrent execution, but there are key differences in how its components handle concurrency. Here's what you need to know:

Thread-Safe: *program.Program

  • Compiled programs are thread-safe and read-only. You can safely reuse a compiled *program.Program across multiple goroutines.
  • Example:
program, err := expr.Compile(`X + Y`)
if err != nil {
    panic(err)
}

// Safe to run in multiple goroutines
go expr.Run(program, Env{X: 1, Y: 2})
go expr.Run(program, Env{X: 3, Y: 4})

Not Thread-Safe: *vm.VM

  • VMs are not thread-safe. Each goroutine should create its own *vm.VM instance.
  • You can manually create a pool of vm machines with *vm.VM.
  • Each expr.Run() call creates a new VM.

Bes…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@rchougule
Comment options

@rchougule
Comment options

@antonmedv
Comment options

Answer selected by rchougule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants