multithreading - 如何编写单元测试来检查方法是否线程安全

标签 multithreading unit-testing go

我有一个这样的对象:

type Store struct {
    mutex sync.RWMutex
    data  map[string]int
}

func (s * Store) Read(key string) int, error {
    // ...
    defer s.mutex.RUnlock()
    s.mutex.RLock()
    // ...
    return val, nil
}

func (s * Store) Write(key string, value int) error {
    // ...
    defer s.mutex.Unlock()
    s.mutex.Lock()
    // ...
    return nil
}

ReadWrite 方法的单元测试应该如何检查它们是否线程安全?

我认为这种情况已经存在模式,但我没有找到任何东西。

我读到关于 -race 标志的内容:

the race detector can detect race conditions only when they are actually triggered by running code, which means it's important to run race-enabled binaries under realistic workloads

我的问题是如何编写模拟实际工作负载的单元测试。

最佳答案

使用 Race detector 运行测试.简而言之,运行:

go test -race

或者构建一个普通的二进制文件,比如在临时服务器上运行,使用:

go build -race

但是还有更多选择,所以最好仔细阅读 :)

如果您的目标是在实际负载下进行测试,最好的选择是使用 go build -race 编译您的代码,然后在实际负载下运行它。这可能意味着在登台服务器上。但是不要将它与单元测试混淆!

单元测试用于测试单元——一小部分代码,通常是单个函数。负载/竞争测试是另一种野兽,需要不同的工具和完全不同的方法。

Go 可以使用竞争检测器轻松运行单元测试这一事实很好,而且经常会出现竞争。但它不会,也不应期望 catch 所有的竞争,因为单元测试执行的性质与生产执行的性质完全不同。

关于multithreading - 如何编写单元测试来检查方法是否线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44728201/

相关文章:

c# - .net 中的异步方法 (!) 说明?

android - 如何停止在线程池执行器 Android 中运行的任务

json - 从 restful API 获取 POST 类型方法的响应

java - 单元测试断言 TreeMap 中的对象顺序正确?

ssl - 带有 GoDaddy 证书的 HTTP SSL - 此服务器的证书链不完整

转到 1.5 到 1.6 : import cycle not allowed

java - 死锁/w ThreadPoolExecutor

c# - 时间限制 C# 中的方法

unit-testing - 单元测试时,是否必须使用数据库来测试 CRUD 操作?

unit-testing - 纽约市报道显示不正确的行号