lipgloss icon indicating copy to clipboard operation
lipgloss copied to clipboard

feat: make Lipgloss Style thread-safe

Open muesli opened this issue 2 years ago • 2 comments

Since we had a few reports about concurrently accessing base style definitions, I figured one solution would be making Style's rules map thread-safe. While it's an elegant solution, it is a trade-off: it guards against crashes from concurrent access, but that obviously slows down access by a tiny bit. I don't think the impact is too bad, though, and not crashing is always nice.

go test -bench=. -benchtime=30s

Before change:

goos: linux
goarch: amd64
pkg: github.com/charmbracelet/lipgloss
cpu: Intel(R) Core(TM) i5-6200U CPU @ 2.30GHz
BenchmarkStyleRender-4           7875594              4555 ns/op
PASS

With sync.map:

goos: linux
goarch: amd64
pkg: github.com/charmbracelet/lipgloss
cpu: Intel(R) Core(TM) i5-6200U CPU @ 2.30GHz
BenchmarkStyleRender-4           7017492              5167 ns/op
PASS

muesli avatar Oct 05 '22 01:10 muesli

Here's one thing I dislike about my own change: this doesn't protect the value member of the Style. This is typically not a problem, because we operate on a copy of Style in critical situations. I can already see future changes invalidating this argument, though, and we would suddenly have to start debugging similar crashes again.

With that being said, maybe an exclusive sync.RWMutex is the better solution for our problem?

muesli avatar Oct 05 '22 01:10 muesli

~We’re deprecating SetString in the instances branch, right? If so, that would deprecate value here, so maybe that’s a non-issue.~

This this is great. It doesn’t appear to impact performance much and the thread-safety it brings is a pretty big deal.

meowgorithm avatar Oct 05 '22 01:10 meowgorithm