Is the expr library concurrency-safe? Is it safe to use it in online concurrent requests?
Is the expr library concurrency-safe? Is it safe to use it in online concurrent requests?
Yes! Expr's vm.Program is thread safe, and concurrency safe.
You can run compiled program in multiple threads via expr.Run().
[!caution] The vm.VM is not thread safe. Although you can use a single vm instance to rerun programs. If needed you can create a vm per thread. The
expr.Run()creates a new vm for each call.
@antonmedv I use this version in our program , github.com/antonmedv/expr v1.15.4 and by my test , this version has concurrency problem , my test code is :
import (
"fmt"
"strconv"
"sync"
"github.com/antonmedv/expr"
)
func main() {
code := `
let a = test_num + 1;
a
`
program, err := expr.Compile(code)
if err != nil {
panic(err)
}
var wg sync.WaitGroup
for i := 0; i < 100000; i++ {
wg.Add(1)
go func(a int) {
defer wg.Done()
env := map[string]interface{}{
"test_num": a,
}
output, err := expr.Run(program, env)
if err != nil {
panic(err)
}
o := output.(int)
if o != a+1 {
fmt.Println(strconv.FormatInt(int64(o), 10) + " " + strconv.FormatInt(int64(a), 10))
}
}(i)
}
wg.Wait()
fmt.Println("end")
}
output is
15487 15519
17906 17900
31508 31510
51443 51426
end
go version go1.20.14 darwin/arm64
but after I upgrade the latest versions , this problem not happen again . I want to confirm does this problem fixed in latest versions?
Yes, the problem was fixed in latest version. We also added race detection tests in our CI pipeline.
@antonmedv Thank you very much for your reply and helpful responses to my questions !
Additionally, could you please provide the commit hash for the problem fix related to our discussion? I'm curious and want to learn 🙏🏻
Thanks again for your hard work! ❤️
Here it is: https://github.com/expr-lang/expr/pull/523 If you're interested in learning more about Expr lets connect on LinkedIn: https://www.linkedin.com/in/anton-medv/