kaspad/util/locks/prioritymutex_test.go
Ori Newman 7c1cb47bd0 [NOD-249] Change WaitGroup to use channels (#350)
* [NOD-248] Implement waitgroup to enable waiting while adding

* [NOD-248] fix waitGroup.done() error message

* [NOD-248] atomically read wg.counter

* [NOD-248] return lowPriorityMutex

* [NOD-249] Add tests to waitgroup

* [NOD-249] Change waitgroup to use channels

* [NOD-249] Format project

* [NOD-249] Add comments and logs to waitGroup, and remove timeouts from
prioritymutex_test.go

* [NOD-249] Fix comments
2019-07-28 18:23:26 +03:00

81 lines
1.7 KiB
Go

package locks
import (
"reflect"
"sync"
"testing"
"time"
)
func TestPriorityMutex(t *testing.T) {
mtx := NewPriorityMutex()
sharedSlice := []int{}
lowPriorityLockAcquired := false
wg := sync.WaitGroup{}
wg.Add(3)
mtx.HighPriorityWriteLock()
go func() {
mtx.LowPriorityWriteLock()
defer mtx.LowPriorityWriteUnlock()
sharedSlice = append(sharedSlice, 2)
lowPriorityLockAcquired = true
wg.Done()
}()
go func() {
mtx.HighPriorityReadLock()
defer mtx.HighPriorityReadUnlock()
if lowPriorityLockAcquired {
t.Errorf("LowPriorityWriteLock unexpectedly released")
}
wg.Done()
}()
go func() {
mtx.HighPriorityWriteLock()
defer mtx.HighPriorityWriteUnlock()
sharedSlice = append(sharedSlice, 1)
if lowPriorityLockAcquired {
t.Errorf("LowPriorityWriteLock unexpectedly released")
}
wg.Done()
}()
time.Sleep(time.Second)
mtx.HighPriorityWriteUnlock()
wg.Wait()
expectedSlice := []int{1, 2}
if !reflect.DeepEqual(sharedSlice, expectedSlice) {
t.Errorf("Expected the shared slice to be %d but got %d", expectedSlice, sharedSlice)
}
}
func TestHighPriorityReadLock(t *testing.T) {
mtx := NewPriorityMutex()
wg := sync.WaitGroup{}
wg.Add(2)
mtx.LowPriorityWriteLock()
isReadLockHeld := false
ch := make(chan struct{})
go func() {
mtx.HighPriorityReadLock()
defer mtx.HighPriorityReadUnlock()
isReadLockHeld = true
ch <- struct{}{}
<-ch
isReadLockHeld = false
wg.Done()
}()
go func() {
mtx.HighPriorityReadLock()
defer mtx.HighPriorityReadUnlock()
<-ch
if !isReadLockHeld {
t.Errorf("expected another read lock to be held concurrently")
}
ch <- struct{}{}
wg.Done()
}()
time.Sleep(time.Second)
mtx.LowPriorityWriteUnlock()
wg.Wait()
}