gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/sync/seqcount_test.go (about) 1 // Copyright 2019 The gVisor Authors. 2 // 3 // Use of this source code is governed by a BSD-style 4 // license that can be found in the LICENSE file. 5 6 package sync 7 8 import ( 9 "testing" 10 "time" 11 ) 12 13 func TestSeqCountWriteUncontended(t *testing.T) { 14 var seq SeqCount 15 seq.BeginWrite() 16 seq.EndWrite() 17 } 18 19 func TestSeqCountReadUncontended(t *testing.T) { 20 var seq SeqCount 21 epoch := seq.BeginRead() 22 if !seq.ReadOk(epoch) { 23 t.Errorf("ReadOk: got false, wanted true") 24 } 25 } 26 27 func TestSeqCountBeginReadAfterWrite(t *testing.T) { 28 var seq SeqCount 29 var data int32 30 const want = 1 31 seq.BeginWrite() 32 data = want 33 seq.EndWrite() 34 epoch := seq.BeginRead() 35 if data != want { 36 t.Errorf("Reader: got %v, wanted %v", data, want) 37 } 38 if !seq.ReadOk(epoch) { 39 t.Errorf("ReadOk: got false, wanted true") 40 } 41 } 42 43 func TestSeqCountBeginReadDuringWrite(t *testing.T) { 44 var seq SeqCount 45 var data int 46 const want = 1 47 seq.BeginWrite() 48 go func() { 49 time.Sleep(time.Second) 50 data = want 51 seq.EndWrite() 52 }() 53 epoch := seq.BeginRead() 54 if data != want { 55 t.Errorf("Reader: got %v, wanted %v", data, want) 56 } 57 if !seq.ReadOk(epoch) { 58 t.Errorf("ReadOk: got false, wanted true") 59 } 60 } 61 62 func TestSeqCountReadOkAfterWrite(t *testing.T) { 63 var seq SeqCount 64 epoch := seq.BeginRead() 65 seq.BeginWrite() 66 seq.EndWrite() 67 if seq.ReadOk(epoch) { 68 t.Errorf("ReadOk: got true, wanted false") 69 } 70 } 71 72 func TestSeqCountReadOkDuringWrite(t *testing.T) { 73 var seq SeqCount 74 epoch := seq.BeginRead() 75 seq.BeginWrite() 76 if seq.ReadOk(epoch) { 77 t.Errorf("ReadOk: got true, wanted false") 78 } 79 seq.EndWrite() 80 } 81 82 func BenchmarkSeqCountWriteUncontended(b *testing.B) { 83 var seq SeqCount 84 for i := 0; i < b.N; i++ { 85 seq.BeginWrite() 86 seq.EndWrite() 87 } 88 } 89 90 func BenchmarkSeqCountReadUncontended(b *testing.B) { 91 var seq SeqCount 92 b.RunParallel(func(pb *testing.PB) { 93 for pb.Next() { 94 epoch := seq.BeginRead() 95 if !seq.ReadOk(epoch) { 96 b.Fatalf("ReadOk: got false, wanted true") 97 } 98 } 99 }) 100 }