Skip to content

Commit

Permalink
hplot: fix race in hplot.New on gonum/plot.DefaultFont
Browse files Browse the repository at this point in the history
Fixes #850.
  • Loading branch information
sbinet committed Dec 16, 2021
1 parent eaeb641 commit c571134
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
7 changes: 7 additions & 0 deletions hplot/plot.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package hplot
import (
"io"
"math"
"sync"

"gonum.org/v1/plot"
"gonum.org/v1/plot/vg"
Expand All @@ -19,9 +20,15 @@ type Plot struct {
Style Style
}

// muNewPlot protects access to gonum/plot.DefaultFont
var muNewPlot sync.Mutex

// New returns a new plot with some reasonable
// default settings.
func New() *Plot {
muNewPlot.Lock()
defer muNewPlot.Unlock()

style := DefaultStyle
defer style.reset(plot.DefaultFont)
plot.DefaultFont = style.Fonts.Default
Expand Down
16 changes: 16 additions & 0 deletions hplot/plot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package hplot_test

import (
"os"
"sync"
"testing"

"go-hep.org/x/hep/hplot"
Expand Down Expand Up @@ -42,3 +43,18 @@ func TestPlotWriterTo(t *testing.T) {
}
}, t, "plot_writerto.png")
}

func TestNewPlotRace(t *testing.T) {
const N = 100
var wg sync.WaitGroup
wg.Add(N)
for i := 0; i < N; i++ {
go func() {
defer wg.Done()

_ = hplot.New()
}()
}

wg.Wait()
}

0 comments on commit c571134

Please sign in to comment.