counter: handle racing situation with mutex
This commit is contained in:
		@ -1,10 +1,15 @@
 | 
				
			|||||||
package counter
 | 
					package counter
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import "sync"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type Counter struct {
 | 
					type Counter struct {
 | 
				
			||||||
	count int
 | 
						count int
 | 
				
			||||||
 | 
						mutex sync.Mutex
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (c *Counter) Inc() {
 | 
					func (c *Counter) Inc() {
 | 
				
			||||||
 | 
						c.mutex.Lock()
 | 
				
			||||||
 | 
						defer c.mutex.Unlock()
 | 
				
			||||||
	c.count++
 | 
						c.count++
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
				
			|||||||
@ -1,6 +1,9 @@
 | 
				
			|||||||
package counter
 | 
					package counter
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import "testing"
 | 
					import (
 | 
				
			||||||
 | 
						"sync"
 | 
				
			||||||
 | 
						"testing"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func assertCounter(t testing.TB, got Counter, want int) {
 | 
					func assertCounter(t testing.TB, got Counter, want int) {
 | 
				
			||||||
	t.Helper()
 | 
						t.Helper()
 | 
				
			||||||
@ -19,4 +22,21 @@ func TestCounter(t *testing.T) {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
		assertCounter(t, counter, 3)
 | 
							assertCounter(t, counter, 3)
 | 
				
			||||||
	})
 | 
						})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						t.Run("it runs safely concurrently", func(t *testing.T) {
 | 
				
			||||||
 | 
							wantedCount := 1000
 | 
				
			||||||
 | 
							counter := Counter{}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							var wg sync.WaitGroup
 | 
				
			||||||
 | 
							wg.Add(wantedCount)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							for i := 0; i < wantedCount; i++ {
 | 
				
			||||||
 | 
								go func() {
 | 
				
			||||||
 | 
									counter.Inc()
 | 
				
			||||||
 | 
									wg.Done()
 | 
				
			||||||
 | 
								}()
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							wg.Wait()
 | 
				
			||||||
 | 
							assertCounter(t, counter, wantedCount)
 | 
				
			||||||
 | 
						})
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
				
			|||||||
		Reference in New Issue
	
	Block a user