github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/sync/mutex_test.go (about) 1 // Copyright 2019 The gVisor Authors. 2 // 3 // Use of this source code is governed by a BSD-style 4 // license that can be found in the LICENSE file. 5 6 package sync 7 8 import ( 9 "sync" 10 "testing" 11 "unsafe" 12 ) 13 14 // TestStructSize verifies that syncMutex's size hasn't drifted from the 15 // standard library's version. 16 // 17 // The correctness of this package relies on these remaining in sync. 18 func TestStructSize(t *testing.T) { 19 const ( 20 got = unsafe.Sizeof(syncMutex{}) 21 want = unsafe.Sizeof(sync.Mutex{}) 22 ) 23 if got != want { 24 t.Errorf("got sizeof(syncMutex) = %d, want = sizeof(sync.Mutex) = %d", got, want) 25 } 26 } 27 28 // TestFieldValues verifies that the semantics of syncMutex.state from the 29 // standard library's implementation. 30 // 31 // The correctness of this package relies on these remaining in sync. 32 func TestFieldValues(t *testing.T) { 33 var m Mutex 34 m.Lock() 35 if got := *m.m.state(); got != mutexLocked { 36 t.Errorf("got locked sync.Mutex.state = %d, want = %d", got, mutexLocked) 37 } 38 m.Unlock() 39 if got := *m.m.state(); got != mutexUnlocked { 40 t.Errorf("got unlocked sync.Mutex.state = %d, want = %d", got, mutexUnlocked) 41 } 42 } 43 44 func TestDoubleTryLock(t *testing.T) { 45 var m Mutex 46 if !m.TryLock() { 47 t.Fatal("failed to aquire lock") 48 } 49 if m.TryLock() { 50 t.Fatal("unexpectedly succeeded in aquiring locked mutex") 51 } 52 } 53 54 func TestTryLockAfterLock(t *testing.T) { 55 var m Mutex 56 m.Lock() 57 if m.TryLock() { 58 t.Fatal("unexpectedly succeeded in aquiring locked mutex") 59 } 60 } 61 62 func TestTryLockUnlock(t *testing.T) { 63 var m Mutex 64 if !m.TryLock() { 65 t.Fatal("failed to aquire lock") 66 } 67 m.Unlock() // +checklocksforce 68 if !m.TryLock() { 69 t.Fatal("failed to aquire lock after unlock") 70 } 71 }