github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/core/bloombits/scheduler_test.go (about) 1 2 //<developer> 3 // <name>linapex 曹一峰</name> 4 // <email>linapex@163.com</email> 5 // <wx>superexc</wx> 6 // <qqgroup>128148617</qqgroup> 7 // <url>https://jsq.ink</url> 8 // <role>pku engineer</role> 9 // <date>2019-03-16 19:16:35</date> 10 //</624450078345531392> 11 12 13 package bloombits 14 15 import ( 16 "bytes" 17 "math/big" 18 "math/rand" 19 "sync" 20 "sync/atomic" 21 "testing" 22 "time" 23 ) 24 25 //测试调度程序可以对检索请求进行重复数据消除和转发 26 //底层的获取器和服务响应返回,与并发无关 27 //请求客户机或服务数据获取程序。 28 func TestSchedulerSingleClientSingleFetcher(t *testing.T) { testScheduler(t, 1, 1, 5000) } 29 func TestSchedulerSingleClientMultiFetcher(t *testing.T) { testScheduler(t, 1, 10, 5000) } 30 func TestSchedulerMultiClientSingleFetcher(t *testing.T) { testScheduler(t, 10, 1, 5000) } 31 func TestSchedulerMultiClientMultiFetcher(t *testing.T) { testScheduler(t, 10, 10, 5000) } 32 33 func testScheduler(t *testing.T, clients int, fetchers int, requests int) { 34 f := newScheduler(0) 35 36 //创建一批处理程序goroutine,以响应bloom位请求和 37 //把它们交给调度。 38 var fetchPend sync.WaitGroup 39 fetchPend.Add(fetchers) 40 defer fetchPend.Wait() 41 42 fetch := make(chan *request, 16) 43 defer close(fetch) 44 45 var delivered uint32 46 for i := 0; i < fetchers; i++ { 47 go func() { 48 defer fetchPend.Done() 49 50 for req := range fetch { 51 time.Sleep(time.Duration(rand.Intn(int(100 * time.Microsecond)))) 52 atomic.AddUint32(&delivered, 1) 53 54 f.deliver([]uint64{ 55 req.section + uint64(requests), //未请求的数据(确保不超出界限) 56 req.section, //请求数据 57 req.section, //重复的数据(确保不会双重关闭任何内容) 58 }, [][]byte{ 59 {}, 60 new(big.Int).SetUint64(req.section).Bytes(), 61 new(big.Int).SetUint64(req.section).Bytes(), 62 }) 63 } 64 }() 65 } 66 //启动一批goroutine以同时运行计划任务 67 quit := make(chan struct{}) 68 69 var pend sync.WaitGroup 70 pend.Add(clients) 71 72 for i := 0; i < clients; i++ { 73 go func() { 74 defer pend.Done() 75 76 in := make(chan uint64, 16) 77 out := make(chan []byte, 16) 78 79 f.run(in, fetch, out, quit, &pend) 80 81 go func() { 82 for j := 0; j < requests; j++ { 83 in <- uint64(j) 84 } 85 close(in) 86 }() 87 88 for j := 0; j < requests; j++ { 89 bits := <-out 90 if want := new(big.Int).SetUint64(uint64(j)).Bytes(); !bytes.Equal(bits, want) { 91 t.Errorf("vector %d: delivered content mismatch: have %x, want %x", j, bits, want) 92 } 93 } 94 }() 95 } 96 pend.Wait() 97 98 if have := atomic.LoadUint32(&delivered); int(have) != requests { 99 t.Errorf("request count mismatch: have %v, want %v", have, requests) 100 } 101 } 102