Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions 102-concurrency/goroutines/race-condition-pointers-fix/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
## How to run Benchmark

* Run this command for Atomic Example.

`$go test -benchmem -run=^$ -bench ^BenchmarkAtomic$`

* Run this command for Mutex Lock Example.

`$go test -benchmem -run=^$ -bench ^BenchmarkMutexLock$`

### Example Results

* **Atomic**
* goos: darwin
* goarch: amd64
* pkg: raceConditionPointersFix
* cpu: Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
* BenchmarkAtomic-4 --- 4977807 --- 236.2 ns/op --- 24 B/op --- 1 allocs/op
* PASS
* ok raceConditionPointersFix 1.895s


* **Mutex Lock**
* goos: darwin
* goarch: amd64
* pkg: raceConditionPointersFix
* cpu: Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
* BenchmarkMutexLock-4 --- 4626063 --- 260.3 ns/op --- 33 B/op 1 allocs/op
* PASS
* ok raceConditionPointersFix 1.592s

3 changes: 3 additions & 0 deletions 102-concurrency/goroutines/race-condition-pointers-fix/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module raceConditionPointersFix

go 1.17
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package raceConditionPointersFix

import (
"fmt"
"sync"
"sync/atomic"
)

type RaceTest struct {
Val int32
}

func main() {
raceTest := &RaceTest{}

wg := &sync.WaitGroup{}
wg.Add(10000)

// mtx := &sync.Mutex{} // This line for mutex lock method

for i:=0; i<10000; i++ {
go incrementWithAtomic(raceTest, wg)
// go incrementWithLock(raceTest, wg, mtx) // This line for mutex lock method
}

wg.Wait()

fmt.Println(raceTest)
}

func incrementWithAtomic(rt *RaceTest, wg *sync.WaitGroup) {
atomic.AddInt32(&rt.Val, 1)
wg.Done()
}

func incrementWithLock(rt *RaceTest, wg *sync.WaitGroup, mtx *sync.Mutex) {
mtx.Lock()
rt.Val += 1
mtx.Unlock()
wg.Done()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package raceConditionPointersFix

import (
"sync"
"testing"
)

// go test -benchmem -run=^$ -bench ^BenchmarkAtomic$
func BenchmarkAtomic(b *testing.B) {
raceTest := &RaceTest{}
wg := &sync.WaitGroup{}
wg.Add(b.N)

for i := 0; i < b.N; i++ {
go incrementWithAtomic(raceTest, wg)
}

wg.Wait()
}

// go test -benchmem -run=^$ -bench ^BenchmarkMutexLock$
func BenchmarkMutexLock(b *testing.B) {
raceTest := &RaceTest{}

wg := &sync.WaitGroup{}
wg.Add(b.N)

mtx := &sync.Mutex{}

for i := 0; i < b.N; i++ {
go incrementWithLock(raceTest, wg, mtx)
}

wg.Wait()
}