Debian Codegraph @

internal/encoder/compiler_race_test.go

raw
1 package encoder
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 opcodes of a type are compiled by every goroutine which encodes the type for the first time at the same
13 // time, and all of them must get the ones which are cached.
14 func TestCompileToGetCodeSetConcurrently(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(struct{ D map[string]int }{}),
20 reflect.TypeOf([]struct{ E *int }{}),
21 }
22 workers := goruntime.GOMAXPROCS(0) * 4
23 results := make([][]*OpcodeSet, 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 ctx := TakeRuntimeContext()
32 defer ReleaseRuntimeContext(ctx)
33 <-start
34 for _, typ := range types {
35 codeSet, err := CompileToGetCodeSet(ctx, uintptr(runtime.TypePtr(typ)))
36 if err != nil {
37 t.Error(err)
38 return
39 }
40 results[i] = append(results[i], codeSet)
41 }
42 }(i)
43 }
44 close(start)
45 wg.Wait()
46
47 ctx := TakeRuntimeContext()
48 defer ReleaseRuntimeContext(ctx)
49 for j, typ := range types {
50 cached, err := CompileToGetCodeSet(ctx, uintptr(runtime.TypePtr(typ)))
51 if err != nil {
52 t.Fatal(err)
53 }
54 if cached.Type != typ {
55 t.Fatalf("expected the opcodes of %s but got the ones of %s", typ, cached.Type)
56 }
57 for i := range results {
58 if len(results[i]) > j && results[i][j] != cached {
59 t.Fatalf("%s: a goroutine got the opcodes which are not cached", typ)
60 }
61 }
62 }
63 }
64
65 func BenchmarkCompileToGetCodeSet(b *testing.B) {
66 typeptr := uintptr(runtime.TypePtr(reflect.TypeOf(struct{ Name string }{})))
67 b.RunParallel(func(pb *testing.PB) {
68 ctx := TakeRuntimeContext()
69 defer ReleaseRuntimeContext(ctx)
70 for pb.Next() {
71 _, _ = CompileToGetCodeSet(ctx, typeptr)
72 }
73 })
74 }