Debian Codegraph @

internal/decoder/compile_race_test.go

raw
1 package decoder
2
3 import (
4 "reflect"
5 goruntime "runtime"
6 "sync"
7 "testing"
8
9 "github.com/goccy/go-json/internal/runtime"
10 )
11
12 // The decoder of a type is compiled by every goroutine which decodes the type for the first time at the same
13 // time, and all of them must get the one which is cached.
14 func TestCompileToGetDecoderConcurrently(t *testing.T) {
15 types := []reflect.Type{
16 reflect.TypeOf(&struct{ A string }{}),
17 reflect.TypeOf(&struct{ B int }{}),
18 reflect.TypeOf(&struct{ C []string }{}),
19 reflect.TypeOf(&map[string]int{}),
20 reflect.TypeOf(&[]struct{ E *int }{}),
21 }
22 workers := goruntime.GOMAXPROCS(0) * 4
23 results := make([][]Decoder, workers)
24
25 start := make(chan struct{})
26 var wg sync.WaitGroup
27 for i := 0; i < workers; i++ {
28 wg.Add(1)
29 go func(i int) {
30 defer wg.Done()
31 <-start
32 for _, typ := range types {
33 dec, err := CompileToGetDecoder(runtime.TypePtr(typ))
34 if err != nil {
35 t.Error(err)
36 return
37 }
38 results[i] = append(results[i], dec)
39 }
40 }(i)
41 }
42 close(start)
43 wg.Wait()
44
45 for j, typ := range types {
46 cached, err := CompileToGetDecoder(runtime.TypePtr(typ))
47 if err != nil {
48 t.Fatal(err)
49 }
50 for i := range results {
51 if len(results[i]) > j && results[i][j] != cached {
52 t.Fatalf("%s: a goroutine got a decoder which is not cached", typ)
53 }
54 }
55 }
56 }
57
58 func BenchmarkCompileToGetDecoder(b *testing.B) {
59 typ := runtime.TypePtr(reflect.TypeOf(&struct{ Name string }{}))
60 b.RunParallel(func(pb *testing.PB) {
61 for pb.Next() {
62 _, _ = CompileToGetDecoder(typ)
63 }
64 })
65 }