Hen*_*nry 0 synchronization unit-testing mutex go
我是 GO 的新手,我不得不在我的代码中使用互斥锁/解锁来防止并发访问。但是在我将 Lock/Unlock 添加到我的代码之后,我的测试开始永远运行。我简化了我的用例并添加了类及其测试文件。如果我单独运行测试,一切都运行良好。但是如果我运行整个文件,前两个就完成了,但第三个永远运行。如果我删除锁定/解锁,那么运行将正确执行。
如果有人能指出我在这里做错了什么,那就太好了。
被测代码:
package anything
import (
"sync"
)
var maxLimit = 5
var Store = Cache{make([]string, 0)}
var mutex = new(sync.RWMutex)
type Cache struct {
items []string
}
func (cache *Cache) Push(item string) {
mutex.Lock()
if len(cache.items) == maxLimit {
cache.items = append(cache.items[:0], cache.items[1:]...)
}
cache.items = append(cache.items, item)
mutex.Unlock()
}
func (cache *Cache) Get(content string) string {
mutex.RLock()
for _, item := range cache.items {
if item == content {
return content
}
}
mutex.RUnlock()
return ""
}
Run Code Online (Sandbox Code Playgroud)
测试文件:
package anything
import (
"github.com/stretchr/testify/assert"
"strconv"
"testing"
)
func TestPush_MoreThanTheMaxLimit_RemoveFirstItem(t *testing.T) {
for i := 0; i <= maxLimit; i++ {
item := strconv.Itoa(i)
Store.Push(item)
}
var actual = Store.items[0]
assert.Equal(t, "1", actual)
}
func TestGet_PresentInCache_ReturnsItem(t *testing.T) {
Store.Push(strconv.Itoa(1))
Store.Push(strconv.Itoa(3))
var actual = Store.Get("1")
assert.Equal(t, "1", actual)
}
func TestGet_NotPresentInCache_ReturnsNil(t *testing.T) {
Store.Push(strconv.Itoa(1))
Store.Push(strconv.Itoa(3))
var actual = Store.Get("7")
assert.Empty(t, actual)
}
Run Code Online (Sandbox Code Playgroud)
如果该Cache.Get()方法找到该项目,它会返回而不调用mutex.RUnlock(),因此互斥锁保持锁定状态。然后Cache.Get()再次调用将阻塞,因为您无法锁定已锁定的互斥锁。
而是使用 解锁defer,因此无论函数如何结束,互斥锁都将被解锁:
func (cache *Cache) Get(content string) string {
mutex.RLock()
defer mutex.RUnlock()
for _, item := range cache.items {
if item == content {
return content
}
}
return ""
}
Run Code Online (Sandbox Code Playgroud)
还要考虑将互斥锁添加到Cache结构本身,因为该互斥锁应该保护对Cache值的并发访问。在您的示例中很好,但是如果您要创建 的多个值Cache,则单个互斥锁将是不够的(会不必要地阻止对所有Cache值的访问,而足以阻止对Cache正在访问的单个值的访问)。嵌入互斥锁也是一个好主意,请参阅何时在 Go中将互斥锁嵌入结构中?
| 归档时间: |
|
| 查看次数: |
164 次 |
| 最近记录: |