github.com/bruceshao/lockfree@v1.1.3-0.20230816090528-e89824c0a6e9/lockfree_test.go (about) 1 /* 2 * Copyright (C) THL A29 Limited, a Tencent company. All rights reserved. 3 * 4 * SPDX-License-Identifier: Apache-2.0 5 * 6 */ 7 8 package lockfree 9 10 import ( 11 "sync" 12 "sync/atomic" 13 "testing" 14 "time" 15 ) 16 17 func BenchmarkLockFree(b *testing.B) { 18 var ( 19 counter = uint64(0) 20 ) 21 eh := &longEventHandler[uint64]{} 22 disruptor := NewLockfree[uint64](1024*1024, eh, &SleepBlockStrategy{ 23 t: time.Microsecond, 24 }) 25 disruptor.Start() 26 producer := disruptor.Producer() 27 var wg sync.WaitGroup 28 wg.Add(b.N) 29 b.ResetTimer() 30 for i := 0; i < b.N; i++ { 31 go func() { 32 for j := 0; j < SchPerGo; j++ { 33 x := atomic.AddUint64(&counter, 1) 34 err := producer.Write(x) 35 if err != nil { 36 panic(err) 37 } 38 } 39 wg.Done() 40 }() 41 } 42 wg.Wait() 43 b.StopTimer() 44 time.Sleep(time.Second * 1) 45 disruptor.Close() 46 } 47 48 func TestChanBlockStrategy(t *testing.T) { 49 var ( 50 counter = uint64(0) 51 goS = 1000 52 perGo = 100 53 ) 54 eh := &longEventHandler[uint64]{} 55 disruptor := NewLockfree[uint64](2, eh, NewChanBlockStrategy()) 56 disruptor.Start() 57 producer := disruptor.Producer() 58 var wg sync.WaitGroup 59 wg.Add(goS) 60 for i := 0; i < goS; i++ { 61 go func() { 62 for j := 0; j < perGo; j++ { 63 x := atomic.AddUint64(&counter, 1) 64 err := producer.Write(x) 65 if err != nil { 66 panic(err) 67 } 68 } 69 wg.Done() 70 }() 71 } 72 wg.Wait() 73 time.Sleep(time.Second * 1) 74 disruptor.Close() 75 } 76 77 func TestCondBlockStrategy(t *testing.T) { 78 var ( 79 counter = uint64(0) 80 goS = 1000 81 perGo = 100 82 ) 83 eh := &longEventHandler[uint64]{} 84 disruptor := NewLockfree[uint64](2, eh, NewConditionBlockStrategy()) 85 disruptor.Start() 86 producer := disruptor.Producer() 87 var wg sync.WaitGroup 88 wg.Add(goS) 89 for i := 0; i < goS; i++ { 90 go func() { 91 for j := 0; j < perGo; j++ { 92 x := atomic.AddUint64(&counter, 1) 93 err := producer.Write(x) 94 if err != nil { 95 panic(err) 96 } 97 } 98 wg.Done() 99 }() 100 } 101 wg.Wait() 102 time.Sleep(time.Second * 1) 103 disruptor.Close() 104 }