Skip to content

Instantly share code, notes, and snippets.

@ilovejs
Forked from liutianpeng/balance_test.go
Created September 4, 2020 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilovejs/9705c0bf03d48f140efc6c2d29e9b145 to your computer and use it in GitHub Desktop.
Save ilovejs/9705c0bf03d48f140efc6c2d29e9b145 to your computer and use it in GitHub Desktop.
消息队列高手课 Mutex,CAS&FAA作业程序
package balance
import (
"runtime"
"sync"
"sync/atomic"
"testing"
)
const MaxCount = 10000
func transfer_Mutex(balance *int32, amount int32, lock *sync.Mutex) {
lock.Lock()
defer lock.Unlock()
*balance = *balance + amount
}
func balance_Mutex() int32 {
wg := &sync.WaitGroup{}
lock := &sync.Mutex{}
balance := int32(0)
for i := 0; i < MaxCount; i++ {
wg.Add(1)
go func() {
defer wg.Done()
transfer_Mutex(&balance, 1, lock)
}()
}
wg.Wait()
//fmt.Println("Balance: ", balance)
return balance
}
func transfer_CAS(balance *int32, amount int32) {
for {
old := atomic.LoadInt32(balance)
new := old + amount
if atomic.CompareAndSwapInt32(balance, old, new) {
break
}
runtime.Gosched()
}
}
func balance_CAS() int32 {
balance := int32(0)
wg := &sync.WaitGroup{}
for i := 0; i < MaxCount; i++ {
wg.Add(1)
go func() {
defer wg.Done()
transfer_CAS(&balance, 1)
}()
}
wg.Wait()
//fmt.Println("Balance: ", balance)
return balance
}
func transfer_FAA(balance *int32, amount int32) {
atomic.AddInt32(balance, amount)
}
func balance_FAA() int32 {
balance := int32(0)
wg := &sync.WaitGroup{}
for i := 0; i < MaxCount; i++ {
wg.Add(1)
go func() {
defer wg.Done()
transfer_FAA(&balance, 1)
}()
}
wg.Wait()
//fmt.Println("Balance: ", balance)
return balance
}
func Test_balance_Mutex(t *testing.T) {
for i := 0; i < 1000; i++ {
if balance_Mutex() != MaxCount {
t.Fail()
}
}
}
func Benchmark_balance_Mutex(b *testing.B) {
for i := 0; i < b.N; i++ {
if balance_Mutex() != MaxCount {
b.Fail()
}
}
}
func Test_balance_CAS(t *testing.T) {
for i := 0; i < 1000; i++ {
if balance_CAS() != MaxCount {
t.Fail()
}
}
}
func Benchmark_balance_CAS(b *testing.B) {
for i := 0; i < b.N; i++ {
if balance_CAS() != MaxCount {
b.Fail()
}
}
}
func Test_balance_FAA(t *testing.T) {
for i := 0; i < 1000; i++ {
if balance_FAA() != MaxCount {
t.Fail()
}
}
}
func Benchmark_balance_FAA(b *testing.B) {
for i := 0; i < b.N; i++ {
if balance_FAA() != MaxCount {
b.Fail()
}
}
}
/*
Benchmark_balance_Mutex-12 300 4262947 ns/op
Benchmark_balance_CAS-12 300 4016430 ns/op
Benchmark_balance_FAA-12 500 3965553 ns/op
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment