atomicerror_test.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package errorx
  2. import (
  3. "errors"
  4. "sync"
  5. "sync/atomic"
  6. "testing"
  7. "github.com/stretchr/testify/assert"
  8. )
  9. var errDummy = errors.New("hello")
  10. func TestAtomicError(t *testing.T) {
  11. var err AtomicError
  12. err.Set(errDummy)
  13. assert.Equal(t, errDummy, err.Load())
  14. }
  15. func TestAtomicErrorNil(t *testing.T) {
  16. var err AtomicError
  17. assert.Nil(t, err.Load())
  18. }
  19. func BenchmarkAtomicError(b *testing.B) {
  20. var aerr AtomicError
  21. wg := sync.WaitGroup{}
  22. b.Run("Load", func(b *testing.B) {
  23. var done uint32
  24. go func() {
  25. for {
  26. if atomic.LoadUint32(&done) != 0 {
  27. break
  28. }
  29. wg.Add(1)
  30. go func() {
  31. aerr.Set(errDummy)
  32. wg.Done()
  33. }()
  34. }
  35. }()
  36. b.ResetTimer()
  37. for i := 0; i < b.N; i++ {
  38. _ = aerr.Load()
  39. }
  40. b.StopTimer()
  41. atomic.StoreUint32(&done, 1)
  42. wg.Wait()
  43. })
  44. b.Run("Set", func(b *testing.B) {
  45. var done uint32
  46. go func() {
  47. for {
  48. if atomic.LoadUint32(&done) != 0 {
  49. break
  50. }
  51. wg.Add(1)
  52. go func() {
  53. _ = aerr.Load()
  54. wg.Done()
  55. }()
  56. }
  57. }()
  58. b.ResetTimer()
  59. for i := 0; i < b.N; i++ {
  60. aerr.Set(errDummy)
  61. }
  62. b.StopTimer()
  63. atomic.StoreUint32(&done, 1)
  64. wg.Wait()
  65. })
  66. }