Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Race on global variable: factorials #368

Open
nasermirzaei89 opened this issue May 13, 2024 · 2 comments
Open

Race on global variable: factorials #368

nasermirzaei89 opened this issue May 13, 2024 · 2 comments

Comments

@nasermirzaei89
Copy link

We get a RACE error on running tests in the production with the flag -race enabled.
And the stack shows it comes from here:

I believe that the reason is multiple goroutines are calling method ExpTaylor and this method manipulates the shared variable factorials (https://github.com/shopspring/decimal/blob/master/decimal.go#L84).
As you used a global variable for caching factorials (#229), it's not goroutine safe and should have a lock.

@mwoss
Copy link
Member

mwoss commented May 14, 2024

Hi @nasermirzaei89! Thanks for bringing this issue up.
I was aware of this potential race condition problem during the implementation of ExpTaylor, but I though my lock-less approach would be sufficient for - https://github.com/shopspring/decimal/blob/master/decimal.go#L1089:L1099. I guess I was wrong, I would need to take a closer look on that 👀

@mqzabin
Copy link

mqzabin commented Jan 2, 2025

We opted to implement our own Taylor Series calculator for exponents in the 1/n format (n being integer). The calculator has its own factorial and Taylor terms cache to avoid RCs/locks/globals. This approach works pretty well, since we work with fixed exponents.

I'm working on moving it to a public repo. Benchmarks are promising:

goos: linux
goarch: amd64
pkg: taylor-bench
cpu: 12th Gen Intel(R) Core(TM) i7-1265U
BenchmarkTaylor/taylor_series_rate_calculator_-_30_digits-12               21740             53317 ns/op           54368 B/op       1476 allocs/op
BenchmarkTaylor/shopspring_-_30_digits-12                                    220           4984208 ns/op         4963830 B/op      10377 allocs/op
PASS
ok      taylor-bench    3.404s

EDIT: This is the repo, but the generics usage is probably affecting the benchmarks.

shermike added a commit to NilFoundation/nil that referenced this issue Jan 31, 2025
Decimal's Pow function is not thread-safe, so we need to lock it manually.
This is a workaround, we need to remove the lock after Decimal will be fixed
or find a better solution.
shopspring/decimal#368
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants