After change the times from 30000 to 300000, the mutex version performance bad as BenchmarkSyncMutex 1594250000 ns/op
but at 30000 the mutex version report 0.01 ns/op just as channel
here is the code
package benchmark
import (
"sync"
"testing"
)
func th1(mu *sync.Mutex, data *int, w *sync.WaitGroup) {
mu.Lock()
*data += 1
mu.Unlock()
w.Done()
}
func BenchmarkSyncMutex(b *testing.B) {
times := 300000 //changed to 30000 will fix the performance problem
mu := new(sync.Mutex)
data := 1
w := new(sync.WaitGroup)
w.Add(times)
for i := 0; i < times; i++ {
go th1(mu, &data, w)
mu.Lock()
data -= 1
mu.Unlock()
}
w.Wait()
println(data)
}
func ch1(c chan int, data *int) {
*data += 1
c <- 1
}
func BenchmarkSyncChannel(b *testing.B) {
c := make(chan int, 100)
data := 1
var s int
times := 300000
for i := 0; i < times; i++ {
go ch1(c, &data)
s += <-c
data -= 1
if s >= times {
break
}
}
println(data)
}
--