SHARE
TWEET

Untitled

a guest Jul 22nd, 2019 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "errors"
  5.     "sync"
  6.     "testing"
  7. )
  8.  
  9. func BenchmarkChannel(b *testing.B) {
  10.     ch := make(chan error, 1)
  11.     for i := 0; i < b.N; i++ {
  12.         wg := sync.WaitGroup{}
  13.         wg.Add(16)
  14.  
  15.         err := errors.New("unknown error")
  16.  
  17.         for i := 0; i < 16; i++ {
  18.             go func() {
  19.                 defer wg.Done()
  20.                 select {
  21.                 case ch <- err:
  22.                 default:
  23.                 }
  24.             }()
  25.         }
  26.  
  27.         wg.Wait()
  28.     }
  29. }
  30.  
  31. func BenchmarkMutex(b *testing.B) {
  32.     var firstError error
  33.     var mutex sync.Mutex
  34.     for i := 0; i < b.N; i++ {
  35.         wg := sync.WaitGroup{}
  36.         wg.Add(16)
  37.  
  38.         err := errors.New("unknown error")
  39.  
  40.         for i := 0; i < 16; i++ {
  41.             go func() {
  42.                 defer wg.Done()
  43.  
  44.                 mutex.Lock()
  45.                 defer mutex.Unlock()
  46.                 if firstError == nil {
  47.                     firstError = err
  48.                 }
  49.  
  50.             }()
  51.         }
  52.  
  53.         wg.Wait()
  54.     }
  55. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top