Created
November 24, 2017 07:37
-
-
Save tenfyzhong/8d5ace93080196a2b4144ddbb6ae6d3a to your computer and use it in GitHub Desktop.
This file contains 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 trylock | |
import "sync/atomic" | |
// Mutex trylock的mutex | |
type Mutex struct { | |
v int32 | |
} | |
// TryLock 尝试获取锁,取不到则返回false | |
func (m *Mutex) TryLock() bool { | |
return atomic.CompareAndSwapInt32(&m.v, 0, 1) | |
} | |
// Unlock 解锁 | |
func (m *Mutex) Unlock() { | |
atomic.StoreInt32(&m.v, 0) | |
} |
This file contains 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 trylock | |
import ( | |
"sync" | |
"testing" | |
) | |
func TestLock(t *testing.T) { | |
m := &Mutex{} | |
if m.v != 0 { | |
t.Fatal("v should be 0") | |
} | |
wg := &sync.WaitGroup{} | |
wg.Add(1) | |
wg2 := &sync.WaitGroup{} | |
wg2.Add(1) | |
go func() { | |
locked := m.TryLock() | |
if !locked { | |
t.Fatal("should be success") | |
} | |
if m.v != 1 { | |
t.Fatal("v should be 1") | |
} | |
wg2.Done() | |
wg.Wait() | |
defer m.Unlock() | |
}() | |
wg2.Wait() | |
if m.v != 1 { | |
t.Fatal("v should be 1") | |
} | |
go func() { | |
locked := m.TryLock() | |
if locked { | |
t.Fatal("should be failed") | |
} | |
}() | |
wg.Done() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment