Created
July 11, 2019 01:13
-
-
Save draveness/f97a12296bd7b19a6c22e45daaee3930 to your computer and use it in GitHub Desktop.
Benchmark Mutex vs Channel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"sync" | |
"testing" | |
) | |
func BenchmarkChannel(b *testing.B) { | |
ch := make(chan error, 1) | |
for i := 0; i < b.N; i++ { | |
wg := sync.WaitGroup{} | |
wg.Add(16) | |
err := errors.New("unknown error") | |
for i := 0; i < 16; i++ { | |
go func() { | |
defer wg.Done() | |
select { | |
case ch <- err: | |
default: | |
} | |
}() | |
} | |
wg.Wait() | |
} | |
} | |
func BenchmarkMutex(b *testing.B) { | |
var firstError error | |
var mutex sync.Mutex | |
for i := 0; i < b.N; i++ { | |
wg := sync.WaitGroup{} | |
wg.Add(16) | |
err := errors.New("unknown error") | |
for i := 0; i < 16; i++ { | |
go func() { | |
defer wg.Done() | |
mutex.Lock() | |
defer mutex.Unlock() | |
if firstError == nil { | |
firstError = err | |
} | |
}() | |
} | |
wg.Wait() | |
} | |
} |
Author
draveness
commented
Jul 11, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment